Separate Compilation of Templates (Classes and Funcions) in C++

It is possible to have templates and separate compilation, but only if you know in advance for which types the template will be instantiated.

If you define the templated classes and functions in the header files themselves or in files included into the header files rather than in separate file, the compiler will not need to resort to separate compilation.

Alternatively, you can instantiate the type definitions you know you will need in the separate file where the template definitions are written. This will then directly be linked to the function calls in the main file. You might name the .cpp file where definitions are written to .inl instead. Then include the .inl file from the bottom of the header file. This yields the same result as defining all functions within the header file but helps keeping the code a little cleaner.

To cause the instantiation of a template class myClass with, say, template parameter double, type:

template class myClass<double>;

The file containing the instantiations of template functions and classes should be compiled into object code (INSTANTIATIONS.o), not fully built.

The code for triggering separate compilation of template functions is analogous. Given a function:

template <typename FLOAT = double>
FLOAT my_sum(FLOAT l, FLOAT r) {return l + r;};

just fully specialize like:

template float my_sum<float>(float l, float r);
]]>