Class Template Instantiation

HomeOverviewHow Do I

Unlike function templates, when instantiating a class template, you must explicitly instantiate the class by giving the arguments for the class templates. To create an instance of TempClass:

TempClass< float, 6 > test1;       // OK
TempClass< char, items++ > test2;  // Error, second parameter 
                                   // must be constant.

No code is generated for a templated class (or function) until it is instantiated. Moreover, member functions are instantiated only if they are called. This can cause problems if you are building a library with templates for other users. See Explicit Instantiation in the C++ Language Reference for more information.

A class template is first specialized and then instantiated by the compiler. The compiler does not instantiate the class template until a reference to a member of this template class is made.

The Visual C++ compiler, in version 5.0 and later, now supports new syntax for explicit specialization of class templates. For example:

template<class T> class X {...};

//Explicit specialization of X with 'int'
//
template<> class X<int> { };

The following form of old syntax is also supported:

//Explicit specialization of X with 'char'
//
class X<char> { };