C++ examples for template:template class
Create Stack Class template
#include <iostream> template <typename T> class Stack {// w w w . j a v a2 s .c o m public: explicit Stack(int = 10); // default constructor (Stack size 10) ~Stack() { delete[] stackPtr; // deallocate internal space for Stack } bool push(const T&); // push an element onto the Stack bool pop(T&); // pop an element off the Stack // determine whether Stack is empty bool isEmpty() const { return top == -1; } // determine whether Stack is full bool isFull() const { return top == size - 1; } private: int size; // # of elements in the Stack int top; // location of the top element (-1 means empty) T* stackPtr; // pointer to internal representation of Stack }; // constructor template template <typename T> Stack<T>::Stack(int s) : size(s > 0 ? s : 10), // validate size top(-1), // Stack initially empty stackPtr(new T[size]) // allocate memory for elements {} // push element onto Stack // if successful return true; otherwise false template <typename T> bool Stack<T>::push(const T& pushValue) { if (!isFull()) { stackPtr[++top] = pushValue; // place item onto Stack return true; } return false; } // pop element off of Stack // if successful return true; otherwise false template <typename T> bool Stack<T>::pop(T& popValue) { if (!isEmpty()) { popValue = stackPtr[top--]; // remove item from Stack return true; } return false; } int main(int argc, const char *argv[]) { Stack<double> doubleStack(5); double doubleValue = 1.1f; std::cout << "Pushing elements onto doubleStack\n"; // push 5 doubles onto doubleStack while (doubleStack.push(doubleValue)) { std::cout << doubleValue << ' '; doubleValue += 1.1; } std::cout << "\nStack is full. Cannot push " << doubleValue << "\n\nPopping elements from doubleStack\n"; // pop elements from doubleStack while (doubleStack.pop(doubleValue)) std::cout << doubleValue << ' '; std::cout << "\nStack is empty, cannot pop\n"; Stack<int> intStack; // default size 10 int intValue = 1; std::cout << "\nPushing elements onto intStack\n"; // push 10 integers onto intStack while (intStack.push(intValue)) { std::cout << intValue++ << ' '; } std::cout << "\nStack is full. Cannot push " << intValue << "\n\nPopping elements from intStack\n"; // pop elements from intStack while (intStack.pop(intValue)) std::cout << intValue << ' '; std::cout << "\nStack is empty. Cannot pop" << std::endl; return 0; }