11.1.  Generics and Templates

[ fromfile: templates.xml id: templates ]

C++ supports four distinct categories of types:

Because there is no common base type for these four distinct type categories, writing generic functions and classes that can operate on multiple type categories would be difficult without the use of templates. Templates provide a means for the C++ compiler to generate different versions of classes and functions with parameterized types and common behavior. They are distinguished by the use of the keyword template, and a template parameter enclosed in angle brackets <>.

A template parameter differs from a function parameter in that it can be used to pass not only variables and values, but also type expressions.

template <class T > class String { ... };
template <class T, int max > Buffer { ...
    T v[max];
};
String <char> s1;
Buffer <int, 10> intBuf10;