*立即 *更新, 具有改进的递归深度!无需增加深度即可在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 ]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)