1 2 3 4 5 6 7 8 9 10 11

Templates
are "patterns" from which classes can be created. A template looks much like an ordinary class, except that part of the class definition is left unspecified. By this means the class is more general and easier to reuse.

Consider the Stacktype of from an earlier lecture. If we translate this type into a C++ class, we might end up with the following definition:
class Stack {
public:
void make_empty();
int is_empty();
void push (int);
int pop ();
....
};
But this Stackcan only store integers. If we later need a stack that stores some other type of data (double values, perhaps, or a structure of some kind, or a pointer variable), then we would have to duplicate the code of Stackto form Istackand Double_Stackand so on. A tedious and error-prone process at best. C++ provides a better idea.
template <class T>
class Stack {
public:
void make_empty();
int is_empty();
void push(T);
T pop();
.....
};

March 14, 1998

Page 3

C201/TAM