Templates - classes parameterised with types

The classes we have used in C++ as part of the course so far have been paramaterised with values, passed in the constructor. The ability to handle different classes of object has been performed either through using a base class from which any object must be derived, as with the list handling classes, or by the highly unsafe use of void* pointers.

The use of inheritance in this way allows a form of polymorphism quite different from that used in functional programming languages such as Standard ML. In SML a function can be defined to handle values of unspecified type. Once the function is used, that use is bound to the type given as actual parameter to match the unspecified type of the formal parameter. This depends on the inbuilt features such as list handling, which are defined over any collection of values of one type.

In C++ a similar form of polymorphism is achieved through a feature known as templates. The most widely used templates are, probably, class templates. These are essentially classes with a second list of parameters, specifying formal type names, which will be bound to actual types when an object is generated from this template.

In addition to types, constant expressions, object addresses and function addresses (not members unless static) may be passed as arguments to templates. In effect a textual substitution is performed when an actual argument is passed.

template class buffer{
   E * buf[size];
public:
   buffer();
   void store(E*);
   E* remove();
};

This defines a class of buffers, where the items to be buffered are not defined. The E* pointer buf will be set to refer to an array holding size E* elements. Examples of uses of this template are:

buffer B1;  // Create buffer of ints, size 1024;

buffer * O_Buf; //Create pointer to buffer of O* size 32;

O_Buf = new buffer; // Types and args must match;

To avoid clumsy repetition of template arguments, a typedef may be used for any type, e.g.:

   typedef buffer char_buf;


Next note in series

Back to index