简体   繁体   中英

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?

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;

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM