Department of Engineering

IT Services

Templates

A class template is a ``type generator'': a way to fabricate many similar classes or functions from one piece of code. This is how the Standard Library can support many types of vector, etc. C++'s Templates are parameterized types. They support generic programming by obviating the need for explicit switch statements to deal with various data types. Let's look at an example. The following code (which doesn't use templates) swaps 2 integers in the usual C++ way

void swap (int& a, int& b) {
   int tmp = a;
   a = b;
   b = tmp;
}

If you wanted to swap other types of variables (including those you've defined) you could copy this code, replacing int by (say) float. But in situations like this, where the code is potentially generic, templates can be used.

template <class T>
void swap (T& a, T& b) {
   T tmp = a;
   a = b;
   b = tmp;
}

Here the ``T" name is arbitrary (like a formal parameter in a function definition) and the class keyword can be replaced by the newer typename keyword. Note that the function is written much as before. When the compiler is now given the following code

   int a = 3, b = 5;
   float f=7.5, g=9.5;
   swap (a, b);
   swap (f, g);

it will create a version (``instantiation") of swap for each type required. These versions have nothing in common except that they were created from the same template - they won't share members, not even static ones. Templates are an example of source code re-use not object code re-use.

You can have template functions, but also template classes and derived classes.