template <typename T, std::size_t Maxsize> classStack { private: std::array<T, Maxsize> elems; // elements std::size_t numElems; // current number of elements public: Stack(); // constructor voidpush(T const& elem); // push element voidpop(); // pop element T const& top()const; // return top element boolempty()const { // return whether the stack is empty return numElems == 0; } std::size_tsize()const { // return current number of elements return numElems; } };
template <typename T, std::size_t Maxsize> Stack<T, Maxsize>::Stack() : numElems(0) // start with no elements { // nothing else to do }
template <typename T, std::size_t Maxsize> void Stack<T, Maxsize>::push(T const& elem) { assert(numElems < Maxsize); elems[numElems] = elem; // append element ++numElems; // increment number of elements }
template <typename T, std::size_t Maxsize> void Stack<T, Maxsize>::pop() { assert(!elems.empty()); --numElems; // decrement number of elements }
template <typename T, std::size_t Maxsize> T const &Stack<T, Maxsize>::top() const { assert(!elems.empty()); return elems[numElems - 1]; // return last element }
intmain() { Stack<int,20> int20Stack; // stack of up to 20 ints Stack<int,40> int40Stack; // stack of up to 40 ints Stack<std::string,40> stringStack; // stack of up to 40 strings
// manipulate stack of up to 20 ints int20Stack.push(7); std::cout << int20Stack.top() << '\n'; int20Stack.pop();
// manipulate stack of up to 40 strings stringStack.push("hello"); std::cout << stringStack.top() << '\n'; stringStack.pop(); }
template <typename T, auto Maxsize> classStack { public: using size_type = decltype(Maxsize);
private: std::array<T, Maxsize> elems; // elements size_type numElems; // current number of elements public: Stack(); // constructor voidpush(T const& elem); // push element voidpop(); // pop element T const &top()const; // return top element boolempty()const// return whether the stack is empty { return numElems == 0; } size_type size()const// return current number of elements { return numElems; } };
// constructor template <typename T, auto Maxsize> Stack<T, Maxsize>::Stack() : numElems(0) // start with no elements { // nothing else to do }
template <typename T, auto Maxsize> void Stack<T, Maxsize>::push(T const& elem) { assert(numElems < Maxsize); elems[numElems] = elem; // append element ++numElems; // increment number of elements }
template <typename T, auto Maxsize> void Stack<T, Maxsize>::pop() { assert(!elems.empty()); --numElems; // decrement number of elements }
template <typename T, auto Maxsize> T const &Stack<T, Maxsize>::top() const { assert(!elems.empty()); return elems[numElems - 1]; // return last element }
通过定义
1 2 3 4 5
template <typename T, auto Maxsize> classStack { ... };