Class Templates

The relationship between a class template and an individual class is like the relationship between a class and an individual object. An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated.

Note the distinction between the terms class template and template class:

Class template a template used to generate template classes. A class template can be only a declaration, or it can be a definition of th e class.
Template class an instance of a class template.
 
A template definition is identical to any valid class definition that the template might generate, except for the following:
A class template can declare a class without defining it by using an elaborated type specifier. For example:
template  <class L,class T> class key;

This reserves the name as a class template name. All template declarations for a class template must have the same types and number of template arguments. Only one template declaration containing the class definition is allowed. You can instantiate the class template by declaring a template class. If the definitions of the member functions of the template class are not inlined, then you have to define them. When you instantiate a template class, its argument list must match the argument list in the class template declaration.

Note: When you have nested template argument lists, you must have a separating space between the > at the end of the inner list and the one at the end of the outer list. Otherwise, there is an ambiguity between the output operator >> and two template list delimiters >.

template  <class L,class T> class key
{
// ...
};
template <class L> class vector
{
// ...
};

void main ()
{
class key <int, vector<int> >; // instantiate template
}

Objects and functions of individual template classes can be accessed by any of the techniques used to access ordinary class member objects and functions.

 



Structuring Your Program Using Templates


Examples of Accessing Class Template Members


Class Template Declarations and Definitions
Nontype Template Arguments
Explicitly Defined Template Classes
Function Templates
Template Syntax
Inlined
Differences between Class and Function Templates
Syntax of a Template Class Instantiation