类模板特化
类模板全特化
常规全特化
对于模板的特化, 需要先有泛化的版本才可以,下面是一些例子
template<typename T1, typename T2>
class Print
{
public:
void show() { cout << "泛化版本" << endl; }
};
template<>
class Print<int, int>
{
public:
void show() { cout << "int特化版本" << endl; }
};
template<>
class Print<char, double>
{
public:
void show() { cout << "char, double特化版本" << endl; }
};
在有泛化的版本Print之下, 才能出现特化的版本,常规全特化是指,所有模板的参数都要用具体的类型代表。
特化成员函数而不是模板
template<typename T1, typename T2>
class Print
{
public:
Print() { cout << "泛化构造函数" << endl; }
void show() { cout << "泛化版本" << endl; }
};
特化成员函数
template<>
void Print<double, double>::show()
{
cout << "特化函数" << endl;
}
Print<double, double> a; // 会调用泛化的构造函数。
a.show(); // 因为我们特化了show函数,所以这里调用的是show的特化函数版本
类模板偏特化(局部特化)
偏特化要从两方面说起:一个是模板参数数量, 一个是模板参数范围
模板参数数量上偏特化
template<typename T1, typename T2, typename T3>
class Print
{
public:
void show() { cout << "泛化版本" << endl; }
};
template<typename T2>
class Print<int, T2, double>
{
public:
void show() { cout << "偏特化版本" << endl; }
};
// 第二个是偏特化版本,也叫局部特化版本,把T1, T3, 绑定到特定类型。T2为任意类型。
具体情况分析
Print<int, int, int> a;
a.show(); // 打印泛化版本
Print<int, double, double> b;
b.show(); // 打印偏特化版本
模板参数范围上偏特化
模板参数范围:如int,const int(比int小), 从int变成const int 类型缩小了,T类型,T* 类型(从任意类型T到指针类型T*范围缩小)
template<typename T>
class Print
{
public:
void show() { cout << "泛化版本" << endl; }
};
template<typename T>
class Print<const T>
{
public:
void show() { cout << "const版本" << endl; };
};
template<typename T>
class Print<T*>
{
public:
void show() { cout << "T*版本" << endl; }
};
Print<int> a;
a.show(); // 泛化版本
Print<const int> b;
b.show(); // const版本
Print<int*> c;
c.show(); // 指针版本
函数模板特化
函数模板全特化:
template<typename T1, typename T2>
void func(T1 & a, T2 & b)
{
cout << "泛化版本" << endl;
}
template<>
void func(int & a, double & b)
{
cout << "全特化版本" << endl;
}
func(4, 9) // 泛化版本
func(4, 8.9) // 特化版本
函数模板没有偏特化。