[C++] Lambda의 Recursive

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!! 
  1. http://www.artima.com/shop/overview_of_the_new_cpp

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다