第三节 · 原地不动 · 深入理解移动操作

模板元编程是利用模板在编译期进行计算的技术。虽然复杂,但能带来零运行时开销的抽象。


编译期计算

// 编译期阶乘
template<int N>
struct Factorial
{
    static const int value = N * Factorial<N - 1>::value;
};

// 特化作为递归终止条件
template<>
struct Factorial<0>
{
    static const int value = 1;
};

int main()
{
    // 编译期计算,运行期直接使用结果
    cout << Factorial<5>::value << endl;   // 120
    cout << Factorial<10>::value << endl;  // 3628800
    
    // 可以用作数组大小
    int arr[Factorial<4>::value];  // int arr[24]
    
    return 0;
}

类型计算


条件类型


类型列表


SFINAE 进阶


编译期字符串


constexpr if(C++17)


concept(C++20)


实际应用:单位系统


习题

  • 实现一个编译期斐波那契数列计算。

  • 使用 SFINAE 检测类型是否可迭代。

  • 用 concept 定义一个"容器"的约束条件。

Last updated