当前位置:  开发笔记 > 编程语言 > 正文

c ++支持模板元编程中的最后一次调用优化

如何解决《c++支持模板元编程中的最后一次调用优化》经验,为你挑选了0个好方法。

我正在阅读有关C++模板的内容,并希望对比一个函数的两种不同实现,它计算从0到N的和.

不幸的是,我遇到了问题,并希望通过示例解决几个问题:

天真的代码:

#include 

template
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);
}

现在我的改进想法是使用累加器:

template
struct 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 ++编译器支持模板元编程的最后调用优化?如果是,为这种优化编写代码的适当方法是什么?

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有