How can I define a template class in separate file ? | SoloLearn: Learn to code for FREE!


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


4/13/2019 1:05:18 AM

Abdelmoumen ED-Daoudy

7 Answers

New Answer


UnViX7 You can do it the following way 1. declare your template in a header file say "stack.h" 2. implement your template definition say "stack.cpp" and in the template header file include the implementation at the end e.g. stack.h template<typename T> class Stack { public: Stack(); void push(T t); }; #include "stack.cpp" // << include implementation your stack.cpp will be like #include "stack.h" //definitions template<typename T> Stack<T> :: Stack() { } template<typename T> void Stack<T> :: push (T t) { } 3. Your work file where you want to use the template #include "stack.h" int main() { Stack <int> iStack; iStack.push(2); }


~ swim ~ UnViX7 If you are going to use the .cpp file as a header, you should probably include include guard in there too.


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.


UnViX7 Forgot to tell , don't forget to use include guard in header file like #ifndef _stack_h_ #define _stack_h_ // template declaration ...... ...... #include "stack.cpp" <-- implementation #endif <-- // close the include guard include guard is used to prevent inclusion of declarations/definition multiple times in a translation unit.


Jared Bird Yeah you are right, forget to mention that too


verio elfando Yeah if you give stress to mods with silly comments like these, you will be banned soon !