特化的目的: 表明该模板在特殊类型下具有不同的行为。
注意:特化的实现可以和基本类模板的实现完全不同。
Stack2.h代码:
#ifndef STACK2_H #define STACK2_H #include <deque> #include <string> #include <stdexcept> #include "TestCC.h" template<> class Stack<std::string> { public: void push(std::string const&); void pop(); std::string top() const; bool empty() const { return elems.empty(); } private: std::deque<std::string> elems; }; void Stack<std::string>::push(std::string const& elem) { std::cout << "Hello World" << std::endl; elems.push_back(elem); } void Stack<std::string>::pop() { if (elems.empty()) throw std::out_of_range("Stack<std::string>::pop(): empty stack"); elems.pop_back(); } std::string Stack<std::string>::top() const { if (elems.empty()) throw std::out_of_range("Stack<std::string>::top(): empty stack"); return elems.back(); } #endif // STACK2_H
测试代码main.cpp:
#include <iostream> #include <string> #include <cstdlib> #include "Stack2.h" using namespace std; int main() { try { Stack<int> intStack; intStack.push(7); cout << intStack.top() << endl; Stack<string> stringStack; stringStack.push("hello"); cout << stringStack.top() << endl; stringStack.pop(); stringStack.pop(); } catch (std::exception const& ex) { cerr << "Exception: " << ex.what() << endl; return EXIT_FAILURE;// n stdlib.h } }
结果: