Predeclaring templates

There are two possible meanings to "predeclare a template". One is to declare that Foo will be a template, similar to saying class Foo. This is done by declaring template class Foo; Foo can now be defined elsewhere, and has the same restrictions as any undefined type. Note that any default template arguments need to be set in the earliest declaration.

The other meaning to this problem is "How do I separate my template class' code from the template in the header, like a normal class defined in a cpp?" C++ does not have a "default" way to do this. The simplest way is shown below. (Note that if Foo is part of a namespace, wrap the contents of the second file in that same namespace)

MyClass.h
//MyClass.h
 * 1) ifndef MyClass_h
 * 2) define MyClass_h

template class Foo { public: Foo; ~Foo;

bool member(int x, int y) const; template bool member_t; };

template void globalfunction;


 * 1) include "MyClass.hpp" //This must be included _after_ the template is declared


 * 1) endif //#ifndef MyClass_h

MyClass.hpp
//MyClass.hpp //The .hpp extension is chosen because compilers tend to either ignore it, //or treat it like a header. Treating it like a source file would be bad.


 * 1) ifndef MyClass_hpp
 * 2) define MyClass_hpp
 * 3) include "MyClass.h" //This is for safety, in case somebody includes the .hpp file directly

template Foo::Foo { //Your code goes here }

template Foo::~Foo { //Your code goes here }

template bool Foo::member(int x, int y) const { //Your code goes here }

template template bool Foo::member_t { //Your code goes here }

template void globalfunction { //Your code goes here }


 * 1) endif //#ifndef MyClass_hpp