我正在阅读有关C++模板的内容,并希望对比一个函数的两种不同实现,它计算从0到N的和.
不幸的是,我遇到了问题,并希望通过示例解决几个问题:
天真的代码:
#includetemplate struct Sum { // Copied the implementation idea from Scott Meyers book // "Effective C++". Is there a better way? enum { value = N + Sum ::value }; }; template<> struct Sum<0> { enum { value = 0 }; }; int main() { // Works well in this case, but gives compilation error, if // it's called with a larger value, such as 10000 // (error: template instantiation depth exceeds maximum of 900"). // How to improve the program properly, that it would // not give compile time error? printf("%d\n", Sum<100>::value); }
现在我的改进想法是使用累加器:
templatestruct Sum { enum { value = Sum ::value }; }; // Is that an appropriate way of writing the base case? template struct Sum { enum { value = Acc }; };
但是,在Ubuntu OS上使用简单的g ++编译时:
int main() { // Still gives the "depth exceeded" error. printf("%d\n", Sum<0, 1000>::value); }
因此,我主要担心的是:
是否有任何现代c ++编译器支持模板元编程的最后调用优化?如果是,为这种优化编写代码的适当方法是什么?