1. 函数特化
template<typename Type>
void template_fun(const Type& t) {
std::cout << "template_fun" << std::endl;
std::cout << t << std::endl;
}
/* 函数特化,
*注意:1.所有特化(包括2、3、4)必须出现在对该模板实例的调用之前,
* 2. 优先选择特化实例,当不匹配时,才选择模板
*/
template<>
void template_fun(const int& num) {
std::cout << "specialized template_fun" << std::endl;
std::cout << num << std::endl;
}
2. 类模板特化
template<typename Type>
class Something {
public:
Something(Type t) :val(t) {}
Type val;
void print(const Type& t);
};
template<typename Type> void Something<Type>::print() {
std::cout << val << std::endl;
}
//类模板特化
template<>
class Something<int> {
public:
Something(int i) :val(i) {}
int val;
// 类模版应该与它特化的模板定义相同的接口
int otherStuff; // available,but inappropriate
void print(int i);
};
// 类外定义函数时无需添加 "template<>"
void Something<int>::print() {
std::cout << "specialized class " << val << std::endl;
}
template<typename Type>
class Something {
public:
Something(Type t) :val(t) {}
Type val;
void print();
};
// 特化成员而不特化类,注意这里与2中print的不同
template<>
void Something<char>::print() {
std::cout << "part specialization!" << val << std::endl;
}
template<typename Type> void Something<Type>::print() {
std::cout << val << std::endl;
}
4. 类模板的部分特化
template<typename T1, typename T2>
class Something {
};
//部分特化,优先选择
template<typename T1, int>
class Something {
};