How can I define a template class in separate file ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

13th Apr 2019, 1:05 AM
Abdelmoumen ED-Daoudy
Abdelmoumen ED-Daoudy - avatar
3 Answers
+ 3
~ swim ~ UnViX7 If you are going to use the .cpp file as a header, you should probably include include guard in there too.
13th Apr 2019, 12:03 PM
Jared Bird
Jared Bird - avatar
+ 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.
13th Apr 2019, 4:27 AM
Jared Bird
Jared Bird - avatar
0
Stress
13th Apr 2019, 3:01 PM
verio elfando