c++ template and header files [duplicate]

Headers.

It's because templates are instantiated at compile-time, not link-time, and different translation units (roughly equivalent to your .cpp files) only "know about" each other at link-time. Headers tend to be widely "known about" at compile-time because you #include them in any translation unit that needs them.

Read https://isocpp.org/wiki/faq/templates for more.


The reason you can't put a templated class into a .cpp file is because in order to "compile" a .cpp file you need to know what the type that is being used in place of T. As it stands a templated class (like your class J) doesn't have enough information to compile. Thus it must be all in headers.

If you want the break up the implementation into another file for cleanliness, the best practice is to use an .hxx file. Like this: inside your header file, J.h, put:

#ifndef _J_H__
#define _J_H__

template <class T> class J{  // member definitions };

#include "j.hxx"

#endif // _J_H__

and then, in j.hxx you'll have

template <class T> J<T>::J() { // constructor implementation }

template <class T> J<T>::~J() { // destructor implementation }

template <class T> void J<T>::memberFunc() { // memberFunc implementation }

// etc.

Finally in your .cpp file that uses the templated class, let's call it K.cpp you'll have:

#include "J.h" // note that this always automatically includes J.hxx    
void f(void)
{
     J<double> jinstance;  // now the compiler knows what the exact type is.
}

Yes, it's true. Declaration and implementation are generally put into the header file all together. Some compilers experimented with an export keyword that would allow them to be separated, but that has been removed from C++0x. Check out this FAQ entry for all the dirty details.


If you need the template code to be usable by other translation units (.cpp files), you need to put the implementation in the .h file or else those other units won't be able to instantiate the template (expand it according to the types they use).

If your template function is only instantiated in one .cpp file, you can define it there. This happens sometimes when a class has a private member function which is a template (and it is only called from the implementation file, not the class header file).