4 specialization 特化
约 244 字小于 1 分钟
2023-08-11
4.1 全特化 full specialization
模板是泛化,特化是泛化的反面,可以针对不同的类型,来设计不同的东西
- 其语法为
template<>
struct xxx<type>
template<>
struct hash<char>
{
...
size_t operator()(char& x) const {return x;}
};
template<>
struct hash<int>
{
...
size_t operator()(int& x) const { return x; }
};
- 这里编译器就会用
int
的那段代码;注意:hash<int>()
是创建临时变量
cout << hash<int>()(1000)
4.2 偏特化 partial specialization
4.2.1 个数上的偏
例如:第一个模板参数我想针对 bool
特别设计

注意绑定模板参数不能跳着绑定,需要从左到右
4.2.2 范围上的偏
例如:想要当模板参数是指针时特别设计

C<string> obj1; //编译器会调用上面的
C<string*> obj2; //编译器会调用下面的