+ 2
How can I define a template class in separate file ?
I want to define a template class in separate file first define the class definition and member function prototype in header file (.h) and the function definition in c++ source file (.cpp) I need help please
3 Answers
+ 2
Templates can be used a few different ways, but if I understand what your trying to do; then you can't. The reason is a template class is not a class of any type; it is template to make any type of class. It may be a subtile difference but its important here. When the compiler finds a definition of a template it doesn't generate any object code, only when it finds an instance of the class (with the type defined) can it generate the class object code. So if a cpp just contained a class template, then nothing would happen, you would still need to add the class template to any other cpp file you wanted to use it. So for std::vector the definition is included in the header, if you make a vector of int, then you can generate in 1 cpp file and use in another.
The exception is when you need multiple types, but you know which types in advance, then you can generate normal classes in a cpp file, and the objects in another. String and wide string are usually normal classes made from the same template class.
0
Stress