/* * C++ array stack using templates. This stack uses a fixed-size array * instead of a list. But it takes the constant array size as a template * parameter. This demonstrates the use of template parameter which takes * a numerical constant. */ #ifndef _STACKT2_H_ #define _STACKT2_H_ // This is a template class. The name T stands for any type. By saying // Stack, we create a stack of whatevers. template class Stack { public: // Create an empty stack. Stack() { m_top_elt = -1; } // Push an element to the stack. Note that push may fail, since // there is only limited space on the stack. Returns true of the // push succeeds. bool push(const T &e) { if(m_top_elt >= size-1) return false; m_data[++m_top_elt] = e; return true; } // Pop an item from the stack. Return T() if the stack is empty. T pop() { if(empty()) return T(); else return m_data[m_top_elt--]; } // An alternate pop which returns through the argument list when the // stack is non-empty (and returns true), but just returns false if // the stack is empty. This can also be more efficient if T is large, // and will work when T has no empty-argument constructor. bool pop(T &ret) { if(empty()) return false; ret = m_data[m_top_elt--]; return true; } // Tell if the stack is empty. bool empty() const { return m_top_elt == -1; } private: T m_data[size]; // The stack contents. int m_top_elt; // The index of the top element. }; #endif