|
|
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 ); }
};
|
|