1

The implementation of a template class must be contained in the header file where it was defined. Should the implementation of such a class be done in-class or regular (like you would to it with every other class) but just in the header file?

The problem i have with the regular approach is that the implementation becomes very bloated since you need to put the template definition infront. I would like to know which is the most common way though.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
  • Code style questions do not go on SO. – ildjarn Apr 12 '12 at 21:17
  • The implementation can be in a cpp file if you know all the types it will be instantiated for, and you instantiate it in that .cpp file. – Peter Wood Apr 12 '12 at 22:32
  • Possible duplicate of http://stackoverflow.com/questions/8662517/do-template-class-member-function-implementations-always-have-to-go-in-the-heade/8662746#8662746 – Bowie Owens Apr 13 '12 at 05:09

1 Answers1

1

Probably the most common way is to write the class definition, then write the implementation in another file, then #include the implementation file at the bottom of the header file and don't list it in the files to be compiled. That way they are in different files but the compiler is satisfied because the definition and declaration is in the same file after preprocessing.

Example:

// header.h

template<typename T>
struct A {
    int dostuff();
};

#include "header.template"

// header.template (not header.cpp, to make it clear that this doesn't get compiled)

template<typename T>
int A::dostuff() { 
   // do stuff
}

After the preprocessor is done, the file looks like

template<typename T>
struct A {
    int dostuff();
};

template<typename T>
int A::dostuff() { 
   // do stuff
}
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249