Recall our discussion of collection classes. If we wanted, for example, a vector of integer, a vector of float, and a vector of some other class, we would have to rewrite the vector class and use aggressive copy and paste (or write a Perl script to munge the text for us).
What we really want is a language mechanism to make a collection "generic" over different types. Some languages have "polymorphic type inference" rules that effectively support generic types automatically, but in C++ we must statically declare the types of all classes and all references in all classes. Therefore, the C++ mechanism is correspondingly more complicated; it's called templates.
To make a function generic, prefix the type declaration with the keyword template, followed by a list of template parameters surrounded by angle brackets:
template T square(T a) { return a * a; } The "T" in the function above is a "type parameter". Despite the "class T" declaration in the template parameter, T may actually be of any type, including primitives.
To use a template function, you may either explicitly or (if no ambiguity exists) implicitly instantiate the template:
int x = square (4); // explicit template instantiation double y = 3.5; double z = square(y); // C++ infers square () This example is trivial, but it demonstrates a couple of interesting points:
Download sample code...
C++ substitutes the appropriate type into the template's code, automaticaly generating an appropriate function. When this happens, C++ will give an error if the * operator is not defined on the type parameter passed to T.
Corollary: any type T that defines
T operator*(T, T); may be used with this template function.