以下库完成的是通过元编程(Meta Programming)直接获得等差数列求和的运行时常量,即从i开始加,i + (i + 1) + (i + 2) + ... + n的工具:
main函数用于测试:
#include <iostream>
using namespace std;
template <int FROM, int TO>
struct IncreaseTo
{
enum { VALUE = FROM + IncreaseTo<FROM + 1, TO>::VALUE };
};
template <int TO>
struct IncreaseTo<TO, TO>
{
enum { VALUE = TO };
};
int main()
{
cout << "The answer is: " << IncreaseTo<1, 10>::VALUE << endl;
cout << "The answer is: " << IncreaseTo<0, 100>::VALUE << endl;
cout << "The answer is: " << IncreaseTo<100, 100>::VALUE << endl;
return 0;
}