如何在编译时驱动C#,C ++或Java编译器来计算1 + 2 + 3 +…+ 1000?

如何在编译时驱动C#,C ++或Java编译器来计算1 + 2 + 3 +…+ 1000?,第1张

如何在编译时驱动C#,C ++或Java编译器来计算1 + 2 + 3 +…+ 1000?

*立即 *更新, 具有改进的递归深度!无需增加深度即可在MSVC10和GCC上运行。:)


简单的编译时递归+加法:

template<unsigned Cur, unsigned Goal>struct adder{  static unsigned const sub_goal = (Cur + Goal) / 2;  static unsigned const tmp = adder<Cur, sub_goal>::value;  static unsigned const value = tmp + adder<sub_goal+1, Goal>::value;};template<unsigned Goal>struct adder<Goal, Goal>{  static unsigned const value = Goal;};

测试码:

template<unsigned Start>struct sum_from{  template<unsigned Goal>  struct to{    template<unsigned N>    struct equals;    typedef equals<adder<Start, Goal>::value> result;  };};int main(){  sum_from<1>::to<1000>::result();}

GCC的输出:

错误:声明’struct sum_from <1u> :: to <1000u> :: equals <500500u>’

有关Ideone的现场示例。

MSVC10的输出:

error C2514: 'sum_from<Start>::to<Goal>::equals<Result>' : class has no constructors      with      [          Start=1,          Goal=1000,          Result=500500      ]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5103954.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存