The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Syntax for Templates

Templates are pretty easy to use, just look at the syntax:

template <class TYPEPARAMTER>

{TYPEPARAMETER} is just the arbitrary typeparameter name that you want to use in your function. Let's say you want to create a swap function that can handle more than one data type...something that looks like this:

template <class SOMETYPE>
void swap (SOMETYPE &x, SOMETYPE &b)
  SOMETYPE temp = a;
  a = b;
  b = temp;

The function you see above looks really similar to any other swap function, with the differences being the template <class SOMETYPE> line before the function definition and the instances of SOMETYPE in the code. Everywhere you would normally need to have the name or class of the datatype that you're using, you now replace with the arbitrary name that you used in the template <class SOMETYPE>. For example, if you had "SUPERDUPERTYPE" instead of "SOMETYPE," the code would look something like this:

template <class SUPERDUPERTYPE>
  x = y;
  y = temp;

As you can see, you can use whatever label you wish for the template typeparameter, as long as it is not a reserved word.

If you want to have more than one template typeparameter, then the syntax would be:

template <class SOMETYPE1, class SOMETYPE2, ...>

Last Update: 2005-12-05