C++ examples for template:template function
Create function template to test template class
#include <iostream> #include <string> template <typename T> class Stack {/*from w ww . jav a2 s. c om*/ 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; } // function template to manipulate Stack<T> template <typename T> void testStack(Stack<T>& theStack, // reference to Stack<T> T value, // initial value to push T increment, // increment for subsequent value const std::string stackName // name of the Stack<T> object ) { std::cout << "\nPushing elements onto " << stackName << '\n'; // push elements onto stack while (theStack.push(value)) { std::cout << value << ' '; value += increment; } std::cout << "\nStack is full. Cannot push " << value << "\n\nPopping elements from " << stackName << '\n'; // pop elements from Stack while (theStack.pop(value)) std::cout << value << ' '; std::cout << "\nStack is empty. Cannot pop" << std::endl; } int main(int argc, const char* argv[]) { Stack<double> doubleStack(5); Stack<int> intStack; testStack(doubleStack, 1.1, 1.1, "doubleStack"); testStack(intStack, 1, 2, "intStack"); return 0; }