/* * File: main.cpp * Author: Administrator * */ #include <iostream> template <typename T> class A { public: void f1(void); static void f2(void); /**模版类中的模版函数,在类模版A未被特化前,虽然可以声明与定义, * 但必须在对应的特化类中重新定义函数!!!顾模版中的模版函数,只需要声明即可, * 具体的定义在模版类被特化后进行!顾,在模版类中声明模版函数没有必要, * 到不如直接在模版类的特化中声明和定义函数模版*/ template <typename E> void f3(void); // { // std::cout << "f3" << std::endl; // } }; /** 模版类成员函数的定义 */ template <typename T> void A<T>::f1(void) { std::cout << "f1" << std::endl; } /** 模版类特化,成员函数的定义 */ template <> void A<int>::f1(void) { std::cout << "f1 int" << std::endl; } /** 模版类'静态'成员函数的定义 */ template <typename T> void A<T>::f2() { std::cout << "f2" << std::endl; } /** 模版类特化,'静态'成员函数的定义 */ template <> void A<int>::f2(void) { std::cout << "f2 int" << std::endl; } /**模版类的特化后*/ template <> class A<double> { public: template <typename E> void f3(void) { std::cout << "f3 A<double>" << std::endl; } }; /**模版类的特化后,对模版函数特化*/ template<> void A<double>::f3<float>(void) { std::cout << "f3 A<double> <float>" << std::endl; } /* * */ int main(void) { A<char> a1; a1.f1(); A<int> a2; a2.f1(); std::cout << "---------------------------" << std::endl; a1.f2(); A<char>::f2(); a2.f2(); A<int>::f2(); std::cout << "---------------------------" << std::endl; // a1.f3(); 错误,因为A<char> 特化类中没有f3() // a2.f3(); 错误,因为A<int> 特化类中没有f3() A<double> a3; // a3.f3(); 错误,没有指明模版函数类型参数 a3.f3<char>(); a3.f3<bool>(); a3.f3<float>(); /**对模版函数特化*/ return 0; }
f1
f1 int
---------------------------
f2
f2
f2 int
f2 int
---------------------------
f3 A<double>
f3 A<double>
f3 A<double> <float>