gardian06
gardian06

Reputation: 1546

turning a non-template class into a template

I have a self made data structure (for example linked list) that works well, but when I made the class I did it based around strings, but now I want to take that data structure, and use it to hold another self made data type. I know that this involves templates (the ability to take a working data structure and apply any data type to it), but I have not really worked with them.

what steps should I follow to turn a non-template class into a template class?

Upvotes: 0

Views: 1308

Answers (2)

Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

that is basic actions

  1. Move all method definitions of your class from .cpp to .h file
  2. Put template specifications (template <class T>) before all declarations and definitions
  3. Change all class name specifiers to template names, i.e. A::A(){} should became A<T>::A(){}
  4. If it required, change the names of method calls to ones with type parameters
  5. Change all entries of the previous type to the type parameter name

can be a lot of the other things of course.

Upvotes: 2

Vaughn Cato
Vaughn Cato

Reputation: 64308

The main thing you need to do is put the template specification in front:

template <class T>
class A {
  ...
};

Then use T instead of using your string type.

There are lots of other things to consider when creating templates, but it depends on the particular situation.

You will specify your new type when you use the template:

A<MyType> my_object;

Upvotes: 2

Related Questions