模板类 template<typename T> stack {...} 的构造函数应该写作stack而不是stack<T>,经作者这么一说我在注意到这件事情。
模板的特化
先说说函数模板。函数模板只能全特化,不能偏特化,并且特化的模板函数相比于等价模板函数优先,但是和非模板函数相比非模板函数优先。
1 #include<iostream> 2 3 using std::cout; 4 using std::endl; 5 6 // version 1 7 int max(int a, int b) 8 { 9 cout << "int max(int, int) is called." << endl; 10 return a > b ? a : b; 11 } 12 13 // version 2 14 template<typename T> 15 T max(const T & a, const T & b) 16 { 17 cout << "template<typename T> T max(const T &, const T &) is called." << endl; 18 return a > b ? a : b; 19 } 20 21 // version 3 22 template<> 23 int max(const int & a, const int & b) 24 { 25 cout << "template<> int max(const int &, const int &)is called." << endl; 26 return a > b ? a : b; 27 } 28 29 int main() 30 { 31 cout << max(1, 2) << endl; // version 1 is called 32 cout << max<>(1, 2) << endl; // version 3 is called 33 cout << max(1.0, 2.0) << endl; // version 2 is called 34 return 0; 35 }
类模板的局部特化
1 #include<iostream> 2 3 using std::cout; 4 using std::endl; 5 6 // version 0 7 template<typename T1, typename T2> class SomeClass 8 { 9 public: 10 SomeClass() 11 { 12 cout << "version 0" << endl; 13 } 14 }; 15 16 // version 1 17 template<typename T> class SomeClass < T, T > 18 { 19 public: 20 SomeClass() 21 { 22 cout << "version 1" << endl; 23 } 24 }; 25 26 // version 2 27 template<typename T> class SomeClass < T, int > 28 { 29 public: 30 SomeClass() 31 { 32 cout << "version 2" << endl; 33 } 34 }; 35 36 // version 3 37 template<typename T1, typename T2> class SomeClass < T1*, T2* > 38 { 39 public: 40 SomeClass() 41 { 42 cout << "version 3" << endl; 43 } 44 }; 45 46 // version 4 47 template<typename T> class SomeClass < T*, T* > 48 { 49 public: 50 SomeClass() 51 { 52 cout << "version 4" << endl; 53 } 54 }; 55 56 57 int main() 58 { 59 // SomeClass<int, int> FirstClass; // Oooooops! This one matches BOTH 2 and 3 -- CONFUSING 60 SomeClass<float*, int*> SecondClass; // version 3 61 SomeClass<int*, int*> ThirdClass; // version 4 -- WITHOUT version 4, this is an error! -- CONFUSING 62 SomeClass<int, char> ForthClass; // version 0 63 SomeClass<char, int> FifthClass; // version 2 64 SomeClass<double, double> FixthClass; // version 1 65 }
所以类模板partial specification有点反直觉的地方。
还有没说到的一点是:可以为类模板参数定义默认值,这些值还可以引用之前的模板参数。
滚去看电动力学@[email protected]
时间: 2024-10-17 23:36:15