聽說模板元編程能在編譯時計算出常量,簡單測試下看看:
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.??