偏特化是指如果一个 class template 拥有一个以上的 template 参数,我们可以针对其中某个(或多个,但不是全部)template 参数进行特化,比如下面这个例子
template <typename T>
class C {...}; //此泛化版本的 T 可以是任何类型
template <typename T>
class C<T*> {...}; //特化版本,仅仅适用于 T 为“原生指针”的情况,是泛化版本的限制版
所谓特化,就是特殊情况特殊处理,第一个类为泛化版本,T 可以是任意类型,第二个类为特化版本,是第一个类的特殊情况。
struct ConstPow 的泛化版本 template <int A, int B> 此时有两个模板参数 A 和 B
特化版本 template struct ConstPow<A, 1> 只有一个模板参数 A
元编程与constexpr 使用模板偏特化为例
#include <iostream>
#include <string>
using namespace std;
template <int A, int B>
struct ConstPow
{
constexpr static int result = A * ConstPow<A, B - 1>::result;
};
template <int A> struct ConstPow<A, 1> { constexpr static int result = A; };
template <int A> struct ConstPow<A, 0> { constexpr static int result = 1; };
int main()
{
cout << ConstPow<2,3>::result << endl;
}