前边提到模版是一个很方便的东西,能让某一个功能不再仅限于某种特定的类型,但是在某些条件下还是会有些不足,在面对特殊的场景,需要对某个变量进行特殊的处理,那么就需要用到模版的特化。
一、什么是模版的特化
在原模板类的基础上,针对特殊类型所进行特殊化的实现方式就是模版的特化,从语义上理解就是给某个特定类型定制一套方案,以免在函数执行的时候出现错误的结果。
二、全特化、偏特化
模版的特化语法大致如下(函数模版为例):
#include<iostream>
using namespace std;
//创建一个模版
template <class T1,class T2>
bool CmpLess(const T1& c1, const T2& c2)
{
cout << "bool CmpLess(const T1& c1, const T2& c2)" << endl;
return c1 < c2;
}
//模版的特化
template<>
bool CmpLess<int>(const int& c1, const int& c2)
{
cout << "bool CmpLess<int>(const int& c1, const int& c2)" << endl;
return c1 < c2;
}
int main()
{
//测试
CmpLess(1, 2);
return 0;
}
运行结果:
模版的特化有两种:一种是“全特化”即把模版参数列表中的所有参数都特化(以上示例),另一种是“偏特化”或者称作“半特化”(函数模板不支持偏特化),即只特化一部分模板参数。值得注意的是全特化是直接写“template<>”,而且特化的参数是要和原模板参数一一匹配的。比如下面的特化就是错误的:
//创建类模板
template <class T1,class T2>
class myclass
{
myclass()
{
cout << "template <class T1, class T2>" << endl;
}
};
//全特化
template <>
class myclass<int>//全特化,但是传入的参数太少
{
myclass()
{
cout << "template <class T1, class T2>" << endl;
}
};
//偏特化
template <class T>
class myclass<int>//偏特化,但是传入的参数太少
{
myclass()
{
cout << "template <class T1, class T2>" << endl;
}
};
总结起来就是:传入的参数是和原模板中的参数一一匹配。
三、非类型模板参数
在模板参数中,可以定义非类型的模板参数,比如:
//函数模板
template <class T1,class T2,int a = 1>
void test1(T1 x,T2 y)
{
cout << "a" << endl;
}
//类模板
template <class T1, int a = 2>
class test2
{
public:
test2()
{
cout << "a" << endl;
}
};
值得注意的是,非类型模板参数只支持整型家族(C20支持浮点数),另外在可以在模板定义的时候给一个缺省参数,那么在使用的时候就不必再次初始化:
int main()
{
//测试
test1(1,1);
test2<int> t;
return 0;
}
运行结果:
如果不写缺省参数,那么在使用的时候必须初始化:
int main()
{
//测试
test1<int,int,100>(1,1);
test2<int,100> t;
return 0;
}
运行结果: