C++/Syntax 2021. 3. 30. 00:01

람다 함수 (Lambda Function)

  • 익명 함수

  • 기본 구조 : -> return type {}

    • [] : 사용할 변수를 지정한다.

      • & : 해당 스코프 변수들을 레퍼런스로 사용한다. 특정 변수명을 &name과 같은 식으로 불러오는 것도 가능하다.

      • = : 해당 스코프 변수들의 값을 복사하여 사용하도록 한다.

      • this : 클래스에서 this를 사용할 때 쓴다.

    • () : 함수의 파라미터를 의미한다.

    • -> : 함수의 반환형을 명시할 수 있다. (생략 시 void)

    • {} : 함수의 body이다.


예제

  • 간단한 숫자, 문자열, 클래스를 출력하는 예제

    #include <iostream>
    #include <string>
    
    class A
    {
        std::string name_ = "default name";
    
    public:
        A() 
        {
            std::cout << "Default Constructor\n"; 
        }
    
        A(const std::string& name)
            : name_(name)
        {}
    
        A(const A& a) 
        {
            std::cout << "Copy Constructor\n"; 
            name_ = a.name_;
        }
    
        void    print() const
        {
            std::cout << name_ << std::endl;
        }
    };
    
    int         main()
    {
        using namespace std;
    
        [](const int& i) -> void { cout << "input : " << i << endl; }(1234);
    
        string name = "Jack Jack";
        [&]() {cout << name << endl; }();
    
        A a("Dash");
        [&]() { a.print(); }();
        [&a]() { a.print(); }();
        [=]() { a.print(); }();
    }
    
    /* stdout stderr
    input : 1234
    Jack Jack
    Dash
    Dash
    Copy Constructor
    Dash
    */
  • 알고리즘 라이브러리와 연계해서 사용하기 좋다.

  • bind() 함수를 이용하여 파라미터를 고정시킬 수도 있다.

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    #include <functional>
    
    int         main()
    {
        using namespace std;
    
        vector<int> v({ 1, 2, 3, 4 });
    
        for_each(v.begin(), v.end(), [](int val) { cout << val << endl; });
    
        std::function<void(int)> func = [](int val) {cout << val << endl; };
        func(123);
    
        std::function<void()> func2 = std::bind(func, 456);
        func2();
    }
    
    /* stdout stderr
    1
    2
    3
    4
    123
    456
    */
  • 멤버 함수를 바인딩할 수도 있다.

    • placeholders는 입력해야 하는 인자의 개수를 의미한다.
    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    #include <functional>
    
    void        goodbye(const std::string& s)
    {
        std::cout << "Goodbye " << s << std::endl;
    }
    
    class Object
    {
    public:
        void hello(const std::string& s)
        {
            std::cout << "Hello " << s << std::endl;
        }
    };
    
    int         main()
    {
        using namespace std;
    
        Object instance;
    
        auto f = bind(&Object::hello, &instance, std::placeholders::_1);
    
        f("World!");
    
        auto f2 = bind(&goodbye, std::placeholders::_1);
    
        f2("World~");
    }
    
    /* stdout stderr
    Hello World!
    Goodbye World~
    */

'C++ > Syntax' 카테고리의 다른 글

C++ delete  (0) 2021.03.15
C++ 깊은 복사(Deep Copy)  (0) 2021.03.15
C++ 얕은 복사(Shallow Copy)  (0) 2021.03.15
C++ 함수 포인터 (Function Pointer)  (0) 2021.03.12
C++ 인라인 함수 (Inline Function)  (0) 2021.03.12