Question

Any one of my C++ projects will generate a linker error unless I include an explicit template instantiation for every templated class/method/function I author and use.

STL classes seem to have no such problem.

Is there some simple code of conduct (pun intended) I can adhere to which allows deferred instantiation like that of STL?

Thanks for listening.

Was it helpful?

Solution

For templates you need to put all the template code and methods into headers rather than source files. The standard library does this.

OTHER TIPS

You should put most parts of a template within the header file. This applies equally to template classes as well as template functions within normal classes.

The exception that you should know to this rule is that when you specialize a template, you need to put the specialization in the implementation/.cpp file because a specialization is a concrete type. The actual template definitions on the other hand will need to be run through multiple times, one for each template parameter type used with the template - so they must go in the header file (they're not concrete type-wise).

e.g. put:

template typename<T> foo(T val) { std::cerr << "DEFAULT"; }

in the header file and its specialization for an int:

template<> foo<int>(int val) { std::cerr << "INT"; }

in the cpp file because the int version is a concrete, fully defined function whereas the T version is a template definition which will be used many time to generate many concrete functions.

Most of the time a template class is defined completely in the header file. This allows the compiler to generate the body of code on the fly if it hasn't already come across the combination of function and template parameters that you're using.

You can still use a template with separate header and implementation files, but it's much less convenient. As you've discovered, you must anticipate each template parameter and put that combination in the implementation file, so that the compiler can generate the necessary code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top