第三节 · 原地不动 · 深入理解移动操作
// 编译期阶乘
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;
}习题
Last updated