-
类模板和函数模板类似,主要用于定义容器类
-
类模板可以偏特化,也可以全特化,使用的优先级和函数模板相同
-
类模板不能隐式推倒,只能显式调用
-
工程建议:
-
模板的声明和实现都在头文件中
-
成员函数的实现在类外
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 template<typename T1, typename T2> //类模板 7 class Test 8 { 9 public: 10 void add(T1 l, T2 r) 11 { 12 cout << "void add(T1 l, T2 r)" <<endl; 13 } 14 }; 15 16 template<typename T> 17 class Test<T, T> //偏特化 18 { 19 public: 20 void add(T l, T r) 21 { 22 cout << "void add(T l, T r)" <<endl; 23 } 24 }; 25 26 template<> 27 class Test<int, int> //全特化 28 { 29 public: 30 void add(int l, int r) 31 { 32 cout << "void add(int l, int r)" <<endl; 33 } 34 }; 35 36 int main() 37 { 38 Test<int, int> t1; 39 t1.add(1, 2); //void add(int l, int r) 40 41 Test<double, double> t2; 42 t2.add(1.5, 2.3); //void add(T l, T r) 43 44 Test<int, double> t3; 45 t3.add(1, 2.5); //void add(T1 l, T2 r) 46 return 0; 47 }
- 在类模板中,类型可以是参数,变量也可以是参数,如复杂度为1计算阶乘
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 template<int N> 7 class Fib 8 { 9 public: 10 static const int value = N * Fib<N-1>::value; 11 }; 12 13 template<> 14 class Fib<1> 15 { 16 public: 17 static const int value = 1; 18 }; 19 20 int main() 21 { 22 cout << "Fib<5>::value = " << Fib<5>::value <<endl; //Fib<5>::value = 120 23 return 0; 24 }
- 上面思路就是C++元编程的核心