// An example of a template specialization // Note the need for a specialized print function #include #include template class Stack { public: Stack() : top_(-1) {} void push(const T& x) { items[++top_] = x; } void pop() { --top_; } T top() const { return items[top_]; } bool empty() const { return top_ == -1; } private: int top_; T items[100]; }; template <> class Stack { public: Stack() : top_(-1) {} void push(const char* x) { char *buf = new char[strlen(x)+1]; strcpy(buf, x); items[++top_] = buf; } const char* top() const { return items[top_]; } void pop() { const char *buf = top(); delete [] buf; --top_; } bool empty() const { return top_ == -1; } private: char* items[100]; int top_; }; template inline const T& max(const T& x, const T& y) { return (x > y) ? x : y; } template void print(Stack & stk) { while (!stk.empty()) { std::cout << stk.top() << std::endl; stk.pop(); } } void print(Stack & stk) { while (!stk.empty()) { std::cout << stk.top() << std::endl; stk.pop(); } } int main() { Stack stk; stk.push(7); stk.push(8); stk.pop(); print(stk); std::cout << max(8, 3) << std::endl; Stack t; t.push("Cat"); t.push("Dog"); print(t); }