Fixed-Size Array-Based Stack
File: stack2.h
/* * 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<whatever>, we create a stack of whatevers. template <typename T, int size = 50> 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

Another way to build a stack is using a fixed-size array to hold the data, and a subscript to say where the top of the stack is. Here we have a template version of one, mainly to show that template parameters are not necessarily type names. The second template parameter is type int, which, for a template parameter, means an integer constant. It also has a default value, as you see.

It has almost the same public interface as the previous stack, except that push can fail, since the stack might be full, so it returns a boolean to indicate success.