HomePage | Recent changes | View source | Discuss this page | Page history | Log in |

Printable version | Disclaimers | Privacy policy

Templates are a feature of C++ generally left out of languages derived from it, such as Java and C#. However, templates are extraordinarily useful, especially when combined with multiple inheritance and operator overloading (two other features generally left out of these newer languages).

A template is a way of substituting an arbitrary data type into a section of code. It works at the time the code is compiled, so that all the normal type-checking still applies.

There are two kinds of templates. A "class template" is often used to make a generic container. For example, the STL (Standard Template Library) has a linked-list container. To make a linked-list of integers, you say "list<int>". A list of strings is denoted "list<string>". A list has a set of standard functions associated with it, which work no matter what you put between the brackets.

There are also function templates. For example, the STL contains the function "max(x,y)", which returns either x or y depending on which is larger. This works whether x and y are integers, strings, or any other type for which it makes sense to say "x < y". If you have defined your own data type, you can use operator overloading to define the meaning of "<" for your type, thus allowing you to use the max function. While this may seem a minor benefit in this isolated example, in the context of a comprehensive library like the STL it allows the programmer to get extensive functionality for a new data type, just by defining a few operators for it.

Any C++ programmer can define generic containers and functions. The STL is written in nothing more than standard C++.