Templates

C++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. This class or function definition generated from a template and a set of template parameters is called a specialization.

Syntax - Template Declaration
 
>>-+--------+--------------------------------------------------->
   '-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 the following kinds of template parameters:

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 L> class Key
{
    L k;
    L* kptr;
    int length;
public:
    Key(L);
    // ...
};

Suppose the following declarations appear later:

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

The compiler would create three objects. The following table shows the definitions of these three objects 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.

Related References

IBM Copyright 2003