[   ^ to index...   |   next -->   ]

CSE 143/AC : 1 August 2000


Templates

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.

Template functions

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 <class T> 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<int>(4); // explicit template instantiation double y = 3.5; double z = square(y); // C++ infers square<double>()

This example is trivial, but it demonstrates a couple of interesting points:

Download sample code...

Last modified: Mon Jul 31 21:17:13 PDT 2000