函数模板的特化
//必须有一个基础模板
template<typename T>
void add(T a, T b) {
cout << "init template" << endl;
}
template<>
void add<int>(int a, int b) {
cout << "special template" << endl;
}
int main() {
add(2.1, 2.2); //init template
add(1, 3); //special template
add<int>(2.1, 2.2); //special template
return 0;
}
对于函数模板不能够处理的特殊类型,一般会定义一个此类型的普通函数,函数模板特化会比较少用,函数模板不支持偏特化
类模板的特化
//特化之前需要存在基础类模板
template<typename T, typename U>
class A {
public:
A() {
cout << "init template" << endl; }
};
//偏特化: 部分特化
template<typename T>
class A<T, int> {
public:
A() {
cout << "part special template" << endl; }
};
//全特化: 所有的参数都为具体类型
template<>
class A<int, int> {
public:
A() {
cout << "all special template" << endl; }
};
int main() {
A<int, int> a; //all special template
A<double, int> b; //part special template
A<double, double> c; //init template
return 0;
}
优先级别:全特化 > 偏特化 > 普通模板
模板调用的选择
template<class T, class U> //原版类模板
class A {
public:
A(T a, U b) : a(a), b(b) {
cout << a + b << endl;
}
T a;
U b;
};
template<class T> //类模板的偏特化 必须在原版模板之后
class A<T, T> {
public:
A(T a, T b) : a(a), b(b) {
cout << a - b << endl;
}
T a, b;
};
/*********************************************************/
template<typename T> //函数模板的(类似重载) 位置不受限制
void func(T a, T b) {
cout << a - b << endl;
}
template<typename T, typename U> //原版函数模板
void func(T a, U b) {
cout << a + b << endl;
}
template<> //函数模板的全特化 必须在原版模板之后
void func(int a, int b) {
cout << a * b << endl;
}
int main() {
//匹配相似度最高的版本
A<int, int> a(1, 1); //0
func(1.0, 1.0); //0
return 0;
}