【发布时间】:2012-10-28 23:05:37
【问题描述】:
我的暂定答案是否定的,如下测试代码所示:
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void TestFunc (void);
int TestFuncHelper (vector<int>&, int, int);
int main (int argc, char* argv[]) {
TestFunc ();
return 0;
} // End main ()
void TestFunc (void) {
// Recursive lambda
function<int (vector<int>&, int, int)> r = [&] (vector<int>& v_, int d_, int a_) {
if (d_ == v_.size ()) return a_;
else return r (v_, d_ + 1, a_ + v_.at (d_));
};
int UpperLimit = 100000; // Change this value to possibly observe different behaviour
vector<int> v;
for (auto i = 1; i <= UpperLimit; i++) v.push_back (i);
// cout << TestFuncHelper (v, 0, 0) << endl; // Uncomment this, and the programme works
// cout << r (v, 0, 0) << endl; // Uncomment this, and we have this web site
} // End Test ()
int TestFuncHelper (vector<int>& v_, int d_, int a_) {
if (d_ == v_.size ()) return a_;
else return TestFuncHelper (v_, d_ + 1, a_ + v_.at (d_));
} // End TestHelper ()
有没有办法强制编译器优化 lambdas 中的递归尾调用?
提前感谢您的帮助。
编辑
我只是想澄清一下,我的意思是问 C++11 是否优化了 lambdas 中的递归尾调用。我使用的是 Visual Studio 2012,但如果绝对知道 GCC 进行了所需的优化,我可以切换环境。
【问题讨论】:
-
你用的是什么编译器; stackoverflow.com/questions/5231823/…似乎表明vs2010可以做一些尾调用,还是你特指lambdas
-
据我所知,该语言对此一无所知。如果您询问特定编译器是否执行此优化,您应该告诉我们您使用的是什么编译器(并且可能重新表述问题)。
-
我正在使用 Visual Studio 2012。是的,正如问题所表明的那样,似乎正在优化实际函数,但不是 lambdas。我想知道是否有一个编译器开关可以用来强制编译器优化 lambdas。
-
抱歉,我错过了
using namespace std;指令。我也错过了前向声明。感谢您指出错误。
标签: c++ lambda c++11 tail-call-optimization