10_specialization 模板特化

specialization 模板特化

specialization 模板特化_

什么叫泛化 ? 泛化就是模板, 模板说我有一个类型, 当你要用的时候再指定这个类型, 这个叫泛化.

与之相对, 特化的意思就是, 你作为一个设计者, 你很可能要为某些特定的类型做独特的设计.

template(class Key)
struct hash { };

比如这个就是一个一般的 泛化, 它接受一个 Key, Key 只是一个符号, 什么类型都可以.

template<>
struct hash<char>
{
    size_t operator() (char x) const { return x; }
};

template<>
struct hash<int>
{
    size_t operator() (int x) const { return x; }
};

template<>
struct hash<long>
{
    size_t operator() (long x) const { return x; }
};

然后 特化, 因为类型被绑定了所以不写 class Key, 也就是尖括号里面不写东西了

它绑定在下面, 意思就是说, 你指定了一个特定的类型, 编译器就会用相应的代码

因此

cout << hash<long>() (1000);

我使用 hash, 尖括号里面是 long, 后面一个空的小括号表示临时对象. 编译器看到这里它就去找, 就决定去用 hash<long> 里面的代码, 后面的括号里面的 1000 就传到里面函数里面去.

partial specialization 模板偏特化 -- 个数的偏

特化又叫作全特化, full specialization

对应过来偏特化叫作 partial specialization, 局部特化, 偏特化

下一节讲偏特化