Templates (C++ only)

A template describes a set of related classes or set of related functions in which a list of parameters in the declaration describe how the members of the set vary. The compiler generates new classes or functions when you supply arguments for these parameters; this process is called template instantiation, and is described in detail in Template instantiation (C++ only). This class or function definition generated from a template and a set of template parameters is called a specialization, as described in Template specialization (C++ only).

Read syntax diagramSkip visual syntax diagramTemplate declaration syntax
 
>>-+--------+--------------------------------------------------->
   '-export-'
 
>--template--<--template_parameter_list-->--declaration--------><
 

The compiler accepts and silently ignores the export keyword on a template.

The template_parameter_list is a comma-separated list of template parameters, which are described in Template parameters (C++ only).

The declaration is one of the following::

The identifier of a type is defined to be a type_name in the scope of the template declaration. A template declaration can appear as a namespace scope or class scope declaration.

The following example demonstrates the use of a class template:

template<class T> class Key
{
    T k;
    T* kptr;
    int length;
public:
    Key(T);
    // ...
};

Suppose the following declarations appear later:

Key<int> i;
Key<char*> c;
Key<mytype> m;

The compiler would create three instances of class Key. The following table shows the definitions of these three class instances if they were written out in source form as regular classes, not as templates:

class Key<int> i; class Key<char*> c; class Key<mytype> m;
class Key
{
      int k;
      int * kptr;
      int length;
public:
      Key(int);
      // ...
};
class Key
{
      char* k;
      char** kptr;
      int length;
public:
      Key(char*);
      // ...
};
class Key
{
      mytype k;
      mytype* kptr;
      int length;
public:
      Key(mytype);
      // ...
};

Note that these three classes have different names. The arguments contained within the angle braces are not just the arguments to the class names, but part of the class names themselves. Key<int> and Key<char*> are class names.