General Stack
File: lstack.h
/* * This is a simple stack template class based on the standard list. */ #ifndef _lstack_h_ #define _lstack_h_ #include <list> using namespace std; /* * This template class implements a standard stack. */ template <typename T> class Stack { public: // Push an item onto the stack. void push(const T & item) { m_data.push_back(item); } // Pop an item from the stack. Return T() if the stack is empty. T pop() { if(m_data.empty()) { return T(); } else { T ret = m_data.back(); m_data.pop_back(); return ret; } } // 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(m_data.empty()) { return false; } else { ret = m_data.back(); m_data.pop_back(); return true; } } // Tell if the stack is empty bool empty() { return m_data.empty(); } private: list<T> m_data; }; #endif /* _lstack_h_ */

A stack based on a vector. Again, the template parameter is a a type (the stack content type). Here, the template is followed by a class, and extends to the end of the class definition. The approach should be familiar from Java generics. The paramter T is a type name, and is used throughout the class to declare data and arguments.

Notice that all of the bodies of methods are present in the class. Templates classes are not generally divided into header and implementation files like plain classes, but must be given entirely in the header.

As with previous examples, this class makes assumptions about what T can do, but they are relatively mild. In particular, the first version of pop assumes that objects of T can be constructed with no parameters, something that is not always true.