lambda 는 자체적으로 recursive 를 사용할 수 없다. overview of the new C++1, slide 80 에서 다음과 같은 구현을 제시한다.
std::function<int(int)> factorial = [&](int x) { return (x==1) ? 1 : (x * factorial(x-1)); };
한 가지 주의할 점이 있다. factorial object 를 다른 std::function<> object 로 복사 한 후에 factorial object 가 파괴되면 bad_function_call 에러가 발생한다.
std::function<int(int)> f; { std::function<int(int)> factorial = [&](int x) { return (x==1) ? 1 : (x * factorial(x-1)); }; f = factorial; } cout<<f(4)<<endl; //bad_function_call!!
- http://www.artima.com/shop/overview_of_the_new_cpp ↩