1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Template functions and classes

In our array implementation of stacks we had two classes: Istack and Cstack. This seems like potentially error-prone work, and duplication to create a new class for every type of object we might want to put on a stack. Templates were invented for just such situations.

#include <assert.h>

template<class T>
class Array_stack {
int sz;
int top;
T*stack;
public:
Array_stack(int Nitems=100)
{ sz = Nitems; stack = new T[sz]; top = sz; }
~Array_stack()
{ delete[] stack; }
void push(Tx)
{ assert( !isfull() ); stack[--top] = x; }
Tpop()
{ assert( !isempty() );
return( stack[top++] ); }
bool isempty()
{ return( top == sz ); }
bool isfull()
{ return( top == 0 ); }
};

22-Mar-98

Page 1

C201/TAM