C++ Programming Guide

Definitions Separate

Another way to organize template definitions is to keep the definitions in template definition files, as shown in the following example.

twice.h

 template <class Number> Number twice( Number original );

twice.cc

 template <class Number> Number twice( Number original ) { return original + original; }

main.cc

 #include "twice.h" int main( ) { return twice<int>( -3 ); }

Template definition files must not include any non-idempotent header files and often need not include any header files at all. (See "Idempotent Header Files" on page 9.)


Note -

Although it is common to use source-file extensions for template definition files (.c, .C, .cc, .cpp, .cxx), template definition files are header files. The compiler includes them automatically if necessary. Template definition files should not be compiled independently.


If you place template declarations in one file and template definitions in another file, you have to be very careful how you construct the definition file, what you name it, and where you put it. You might also need to identify explicitly to the compiler the location of the definitions. Refer to C++ User's Guide for information about the template definition search rules.