我試探性的答案是否定的,通過下面的測試代碼觀察:C++ 11是否優化了lambdas中的尾遞歸調用?
#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()
有沒有辦法強制編譯器優化的lambda表達式的遞歸尾調用?
在此先感謝您的幫助。
編輯
我只是想澄清,我的意思是問,如果C++ 11優化了lambda表達式的遞歸尾調用。我使用的是Visual Studio 2012,但如果絕對知道GCC執行所需的優化,則可以切換環境。
你正在使用什麼編譯器; http://stackoverflow.com/questions/5231823/vs2010-c-tail-call-optimization?rq=1似乎表明,vs2010可以做一些尾巴呼叫,或者你是否特別提到lambdas – Foon
該語言,儘可能我知道,對此沒有提及。如果你問一個特定的編譯器是否執行這種優化,你應該告訴我們你正在使用什麼編譯器(並且可能會重新解釋這個問題)。 –
我正在使用Visual Studio 2012.是的,正如問題所示,看起來實際功能正在優化,但不是lambda。我想知道是否有一個編譯器開關可以用來強制編譯器優化lambda表達式。 – Shredderroy