听说模板元编程能在编译时计算出常量,简单测试下看看:
cpp
template<int N>
struct Summation {
static constexpr int value = N + Summation<N - 1>::value; // 计算 1 + 2 + ... + N 的值
};
template<>
struct Summation<1> { // 递归终止条件
static constexpr int value = 1;
};
constexpr int result = Summation<5>::value; // 即 5 + 4 + 3 + 2 + 1 = 15;
int main()
{
cout << "1 + 2 + ... + 5 = " << Summation<5>::value << endl;
return 0;
}
打印:

ok.