模板的特化是指:在使用泛型中需要对一些特定的类型进行特定的处理。
如下代码所示:
#include <iostream>
template<class Key>
struct Hash {
Hash()
{
std::cout << " hash key!";
}
};
//模板的特化
template<>
struct Hash<long> {
Hash<long>()
{
std::cout << " hash long!" << std::endl;
}
size_t operator()(long l)
{
return sizeof(l);
}
};
template<>
struct Hash<int> {
Hash<int>()
{
std::cout << " hash int!" << std::endl;
}
size_t operator()(int i)
{
return sizeof(i);
}
};
int main()
{
int a = 10;
//输出结果:hash int! 4
std::cout << Hash<int>()(a);
return 0;
}
在指定了模板类型为int后,编译器会自动找到特化的模板类。
注:Hash<int>()(a)中第一个()调用了Hash<int>的构造函数,第二个()则调用了重载()符号函数
模板的偏特化:是与泛化(full specialization)相对的局部特化(partial specialization),偏特化可以分类两类:即从参数的个数进行特化与参数的范围上进行特化。
第一类,对参数的个数上进行特化:
template<typename T,typename Alloc>
class Vector{
};
template<typename Alloc>
class Vector<bool,Alloc>{
};
上述代码从参数的个数上进行了偏特化,Vector<bool>对第一个参数typename T进行的特定,将T特定为bool类型。
下面的代码是对范围进行了偏特化。将任意参数T增加了一个特化版本T*,即T的指针,如果指定了C<任意类型的指针>则会调用特化版本
template<typename T>
class C{
};
template<typename T>
class C<T*>{
};