// stack class from Effective C++, Scott Meyers #include #include template class stack { private: struct stacknode { T data; stacknode *next; stacknode(const T& newdata, stacknode *nextnode) : data(newdata), next(nextnode) { } }; stacknode *top; public: stack(); ~stack(); void push(const T& object); T pop(void); }; template stack::stack() : top(0) { } template stack::~stack(void) { while (top) { stacknode *next_to_die = top; top = top->next; delete next_to_die; } } template void stack::push(const T &object) { top = new stacknode(object, top); if(!top) { cout << "\ndynamic memory exhausted\n"; exit(1); } } template T stack::pop(void) { static T safe; if (!top) { cout << "\n attempt to pop empty stack\n"; return safe; } stacknode *save = top; top = top->next; T data = save->data; delete save; return data; } /* */ //----< test stub >------------------------------------------// template void print_field(T t) { cout.width(10); cout << t; } void main() { cout << "\nTesting Template Based Stack Class\n\n"; stack int_stack; stack double_stack; int x=1, y=2, z=3; double u=-1.5, v=0.5, w=2.5; int_stack.push(x); int_stack.push(y); int_stack.push(z); double_stack.push(u); double_stack.push(v); double_stack.push(w); print_field(int_stack.pop()); print_field(int_stack.pop()); print_field(int_stack.pop()); cout << "\n"; print_field(double_stack.pop()); print_field(double_stack.pop()); print_field(double_stack.pop()); cout << "\n"; int_stack.pop(); double_stack.pop(); cout << "\n\n"; }