その先にあるもの…

[C++]C++ 람다 본문

프로그래밍

[C++]C++ 람다

specialJ 2016. 6. 8. 18:18

람다 식의 구조 요소

[캡처] (매개변수 목록) mutable 예외목록 -> 반환형 { 함수 몸체 }




에러가 나지 않지만 출력은 되지 않는다.
[] {};
[] {std::cout << "Hello World" << std::endl; };

마지막에 ()를 붙여 함수를 호출한다.
[] { std::cout << "Hello World<< std::endl; }();

//auto로 받아 호출할 수 있다.
auto f = [] { std::cout << "Hello World 1" << std::endl;};
f();



[캡처]

람다 함수 외부의 변수에 접근할 수 예약어

[] 외부 변수를 쓰지 않는다.

[=] 모든 외부 변수를 값으로 전달 받는다.

[&] 모든 외부 변수를 참조로 전달 받는다.

[this] 현재 객체를 참조한다.



int nOutValue = 1;


for (int i = 0; i < 10; ++i)

{

[]()

{

//에러 외부 변수 nOutValue에 접근하지 못한다.

std::cout << "Hello World ~ " << nOutValue++ << std::endl;

}();

}



for (int i = 0; i < 10; ++i)

{

[=] ()

{

   //에러 외부 변수 nOutValue를 수정하지 못한다.

std::cout << "Hello World ~ " << nOutValue++ << std::endl;

}();

}



for (int i = 0; i < 10; ++i)

{

[&] ()

{

   //1에서 10까지 출력된다.

std::cout << "Hello World ~ " << nOutValue++ << std::endl;

}();

}



int n1, n2, n3, n4, n5;

[]() { n1 = 10; }();   Error
[&, n1, n2] {}; //n3, n4, n5 참조, n1, n2 복사
[=, &n1, &n2] {}; //n3, n4, n5 복사, n1, n2 참조
[&n1, &n2] {n3 = 10; }; //Error
[n1, n1] {};     //Error 같은 변수
[&, &n1] {};    //Error n1 default 이미 사용

(매개변수)
함수의 인자 리스트

auto f= [](int n) { std::cout << "value  " << n << std::endl; };
f1(3);
f1(6);
f1(9);

mutable

값으로 전달받아서 캡처하는 방식일 때 한정자 const를 무효화 시킨다.


for (int i = 0; i < 10; ++i)

{

[=] () mutable

{

   //값에 의한 전달이라 Hello World ~ 1이 10번 출력된다.

std::cout << "Hello World ~ " << nOutValue++ << std::endl;

}();

}


예외처리

throw로 예외를 넘길 수 있다.


for (int i = 0; i < 10; ++i)

{

try {

[&]() mutable throw()

{

std::cout << "Hello World ~ " << nOutValue++ << std::endl;

throw 1;

}();

}

catch (int e) {

//error가 10번 찍힌다.

if (e == 1)

std::cout << "erro" << std::endl;

}

}



반환형
리턴 데이터 타입

for (int i = 0; i < 10; ++i)
{
[&]() mutable throw() -> int
{
std::cout << "Hello World ~ " << nOutValue++ << std::endl;
return nOutValue;
}();
}

int nReturn = [] {return 3.14f; }();        //nReturn은 3
float fReturn = []() {return 3.14f; }();    //fReturn은 3.14
float fReturn = []()->float {return 3.14f; }();    //fReturn은 3.14


템플릿 함수의 자로 사용되어 호출될 수 있다.
template<typename T>
void templateFunc(T t)
{
t();
}

templateFunc(f);


stl에서 람다 사용
std::vector<int> vector1;
vector1.push_back(10);
vector1.push_back(20);
vector1.push_back(30);
std::for_each(vector1.begin(), vector1.end(), [](int n) {std::cout << n << std::endl; });


리턴형이 람다인 함수 사용
std::function< void() > ff()
{
std::string str("lambda");
return [=] { std::cout << "Hello " << str.c_str() << std::endl; };
}
auto func = ff();
func();
ff()();


클래스안에 람다함수 - firend
class Clambda
{
public:
int m_public = 10;
int publicFunc() { return m_public; }
private:
int m_private = 20;
int privateFunc() { return m_private; }

public:
Clambda() {}
std::function< void() > m_function()
{
return [this]() { m_public = 20; m_private = 30; };
}

void print() 
{
std::cout << m_public << " " << m_private << std::endl;
}
};

Clambda lambda;
lambda.m_function()();
lambda.print();

제너릭처럼 사용
auto sum = [](auto a, auto  b) { return a + b; };
int i = sum(3, 6);
double d = sum(3.14, 2.77);

캡쳐하지 않은 람다는 함수 포인터로 형 변환 가능
auto L = [](auto a, auto b) { return a + b; };
int(*pf)(int, int) = L;
int p = (*pf)(1, 2);

'프로그래밍' 카테고리의 다른 글

[SHELL SCRIPT] 쉘 스크립트 scp 예제  (0) 2018.03.29
[SHELL SCRIPT] 쉘 프로그램  (0) 2018.03.14
[C++] default delete  (0) 2016.06.08
[C++]초기화 리스트  (0) 2016.06.08
[C++]Range based for loop  (0) 2016.06.08
Comments