7. int main()
{
// 1. 람다 함수를 반환 값으로 한다.
auto g = [](int x) -> function<int (int)>
{
return [=](int y) { return x + y; };
};
// 2. 람다 함수를 입력 값으로 받는다.
auto h = [](const function<int (int)>& f, int z)
{
return f(z) + 1;
};
auto a = h( g(7), 8 );
cout << a << endl;
}
8. 람다는 Closure
Closure 란?
함수를 호출한 상위 코드 블록의 변수들이 호출된 함수
와 묶인 것을 뜻합니다.
즉 호출된 함수는 상위 코드 블록 의 외부 변수와 묶여
자기만의 상태를 갖게 되는 것입니다.
9. void capture()
{
int a = 0;
int b = 1;
int c = 2;
// 1. default 값 복사 캡처. 상위 코드 블록의 지역 변수 모두 값 복사 가능
[=](){ cout << a << “ “ << b << endl; }(); // 0 1 출력
// 2. default 값 참조 캡처. 상위 코드 블록의 지역 변수 모두 값 참조 가능
[&](){ cout << a << “ “ << b++ << endl;}(); // 0 1 출력
// 3. default 값 복사 캡처, b와 c 참조 캡처
[=, &b, &c](){ cout << a << “ “ << b << “ ” << c << endl; }(); // 0 2 2 출력
}
11. lambda-introducer (referred to as capture clause later in this topic)
lambda-parameter-declaration-list (referred to as parameter list later in this topic)
mutable-specification (referred to as mutable specification later in this topic)
exception-specification (referred to as exception specification later in this topic)
lambda-return-type-clause (referred to as return type later in this topic)
compound-statement (referred to as lambda body later in this topic)
예를 들어보자
13. mutable 은 머냐?
람다 캡쳐에서 값으로 복사한 변수의 값을 변경시킬 수 있다.
int x = 10;
// mutable 을 선언하지 않으면 x 의 값을 변경시킬 수 없다.
[=] () mutable { x = 20; };
// 하지만 x 는 여전히 10
cout << x << endl;
14. 값 복사시 const 속성을 잃는다.
const int M = 10;
int x[M]; // OK
[=] () {
int y[M]; // !Error
int* z = new int[M]; // OK
};
15. 언제 써먹나?
1. fuctor 보다 편하다.
- functor 만들기 귀찮아서 안쓰던 for_each 같은 함수들 쓰기 좋아진다
2. fuction 을 벡터나 큐에 넣어서 Async 하게 호출 할 때 쓴다
3. Call 하는 쪽에서 함수의 Context 를 정의할 수 있다.
4. Async 콜의 경우 함수가 뚝뚝 떨어져서 가독성을 떨어트리는데, 한곳에
기능을 적을 수 있다.
16. 4번에 대한 추가 설명
기존 방식
void Request()
{
Async_test1();
}
void Async_test1()
{
// 할 일 들..
Async_test2();
}
void Async_test2()
{
// 할일 들2
}
람다를 쓸 경우
void Request()
{
Async_call([]() {
// 할 일들
Async_call([](){
// 할 일들 2
});
});
}
함수 동작이 한 눈에 보인다