// Arup Guha // 3/4/02 // This is an example of how templates are used // to define a polymorphic stack #include template class stack { int count; T elems[100]; public: stack() {count = -1;}; char empty() {return count == -1;}; void push(T e); T pop(); T current(); void print(); stack add(stack s); stack operator+(stack s); }; template void stack::push(T e) { if (count >= 99) exit(-1); else elems[++count] = e; } template T stack::pop() { if ( empty() ) exit(-2); else return (elems[count--]); } template T stack::current() { return (elems[count]); } template void stack::print() { int i; for (i=0;i <= count;i++) cout << " " << elems[i] << " "; cout << "\n"; } template stack stack::add(stack s) { if (count != s.count) exit(-3); else { stack temp; int i; // Adds corresponding elements together and stores into the new stack. for (i=0;i <= count;i++) temp.elems[i] = elems[i] + s.elems[i]; temp.count = count; return temp; } } template stack stack::operator+(stack s) { return add(s); } main() { // Test a simple stack s. stack s; int temp; temp = 1; s.push(temp); temp = 2; s.push(temp); temp = s.pop(); cout << "Value is " << temp << "\n"; // Create more stacks to test. stack s1; stack f,f1; cout << s.empty() << endl; // Add to stack s. s.print(); s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); s.print(); // Create s1 from s+s. s1=s.add(s); s1.print(); // Get rid of elements in s. temp = s.pop(); cout << "Temp is " << temp << "\n"; s.print(); s.pop(); s.print(); s.pop(); s.print(); s.pop(); s.print(); cout << " === " << s.pop() << " ===" << endl; s.print(); // Add elements to stack f. cout << f.empty() << endl; f.print(); f.push(1.4); f.push(2.4); f.push(3.4); f.push(4.4); f.push(5.4); f.print(); // Create stack f1. f1=f + f; f1.print(); // Pop off elements from f. f.pop(); f.print(); f.pop(); f.print(); f.pop(); f.print(); f.pop(); f.print(); cout << " === " << f.pop() << " ====" << endl; f.print(); } /******** Output ******* Value is 2 1 1 1 2 3 4 5 2 2 4 6 8 10 Temp is 5 1 1 2 3 4 1 1 2 3 1 1 2 1 1 === 1 === 1 1.4 2.4 3.4 4.4 5.4 2.8 4.8 6.8 8.8 10.8 1.4 2.4 3.4 4.4 1.4 2.4 3.4 1.4 2.4 1.4 === 1.4 ==== ****************************/