次のテスト コードで観察されるように、私の暫定的な答えはノーです。
#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 ()
ラムダで再帰的な末尾呼び出しを最適化するようにコンパイラに強制する方法はありますか?
よろしくお願いします。
編集
C++11 がラムダの再帰的な末尾呼び出しを最適化するかどうかを尋ねるつもりだったことを明確にしたかっただけです。私は Visual Studio 2012 を使用していますが、GCC が目的の最適化を行うことが確実にわかっている場合は、環境を切り替えることができます。