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

标签 c++

我正在阅读有关 C++ 模板的内容,并且想对比计算从 0 到 N 的总和的函数的两种不同实现方式。

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

朴素求和代码:

#include <stdio.h>

template<int N>
struct Sum {
    // Copied the implementation idea from Scott Meyers book
    // "Effective C++". Is there a better way?
    enum { value = N + Sum<N - 1>::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<int Acc, int N>
struct Sum {
    enum { value = Sum<Acc + N, N - 1>::value };
};

// Is that an appropriate way of writing the base case?
template<int Acc> 
struct Sum<Acc, 0> {
    enum { value = Acc };
};

但是,当在 Ubuntu 操作系统上使用简单的 g++ 编译时:

int main() {
    // Still gives the "depth exceeded" error.
    printf("%d\n", Sum<0, 1000>::value);
}

因此,我主要关心的是:

是否有任何现代 c++ 编译器支持最后一次调用优化 模板元编程?如果是,为此类优化编写代码的合适方法是什么?

最佳答案

Does any modern c++ compiler support last call optimisation for template metaprogramming? If yes, what is an appropriate way to write code for such optimisation?

不,这没有意义。模板实例化不是函数调用...最后/尾部调用优化与此处无关。与函数调用不同,模板实例化不是 transient 的,自动变量可以回收;相反,每个模板实例化都成为编译器状态下的新类型。

关于c++ 支持模板元编程中的最后一次调用优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088049/

相关文章:

c++ - map 的开始迭代器不起作用 C++

c++ - 为什么没有 1 :1 relationship between assignment and equality operators?

c++ - 函数调用另一个函数的时间复杂度?

c++ - 需要帮助在 C++ 中进行多线程

c++ - 线程模型和类实例内存管理

c++ - 使用 opengl 2 从鼠标转换光线

c++ - 当一个结构有 c-tor 时,为什么我不能静态初始化它?

c++ - 2D游戏 map 移动

c++ - vtable 存储在内存的哪个位置?

c++ - 使用 const 关键字重载签名相同的方法