Sun Studio 12: C++ User's Guide

5.2.2 Template 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


#ifndef TWICE_H
#define TWICE_H
template <class Number>
Number twice(Number original);
#endif TWICE_H

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 5.1.2 Idempotent Header Files.) Note that not all compilers support the definitions-separate model for templates.

Because a separate definitions file is a header file, it might be included implicitly in many files. It therefore should not contain any function or variable definitions, unless they are part of a template definition. A separate definitions file can include type definitions, including typedefs.


Note –

Although source-file extensions for template definition files are commonly used (that is, .c, .C, .cc, .cpp, .cxx, or .c++), 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 7.5 Template Definition Searching” for information about the template definition search rules.