An important form of polymorphism in C++ is the ability to describe a class that has parameters that can specialize its use. A template is a class declaration with one or more parameter names embedded in it that can be replaced at compile-time by an argument.
For instance, part of a class that encapsulates an integer array might be:
class X { private: int array[100]; ... };
The type of the array is fixed. However, by turning the declaration into a template, the class can then be made to contain an array of any type:
template<class T> class X { private: T array[100]; ... };This no longer a class declaration, but a template for a family of class declarations. To use the template, the parameter must be instantiated:
X obj1<int>;makes an object of type X<int>, whereas:
X obj2<float>;makes an object of type X<float>, and:
X obj2<Y>;makes an object of type X<Y>, where Y is a previously-defined class.
Global functions can also be templated, e.g.
template<class T, int size> void process(T a[]) { for (int i = 0; i < size; i++) a[i] *= 2; }
Copyright © 2003 Roger Hartley