일상 코딩
[C++/CPP] 19.01 모던 C++ lambda function, std::function, std::bind, std::placeholders 본문
      C++/따배C++ 19강 모던 C++ 기능들
      
    [C++/CPP] 19.01 모던 C++ lambda function, std::function, std::bind, std::placeholders
polarcompass 2021. 12. 11. 06:26728x90
    
    
  #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(int argc, char const *argv[])
{
    // lambda-introducer
    // lambda-parameter-declaration
    // lambda-return-type-clause
    // compound-statement
    using namespace std;
    auto func = [](const int& i) -> void {cout << "Hello, World!" << endl;};
    func(123);
    [](const int& i) -> void { cout << "Hello, World!" << endl;}(1234);
    
    {
        // [&] : name을 참조해서 가져올 수 있음.
        string name = "JackJack";
        [&](){cout << name << endl;}();
        // [=] : name을 복사해서 가져올 수 있음.
        name = "sudo";
        [=](){cout << name << endl;}();
    }
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    // 예전 방식
    auto func2 = [](int val) {cout << val << endl;};
    for_each(v.begin(), v.end(), func2);
    // 최신 방식
    for_each(v.begin(), v.end(), [](int val){cout << val << endl;});
    cout << []() -> auto { return 10;}() << endl;
    // function pointer
    std::function<void(int)> func3 = func2;
    func3(123);
    std::function<void(void)> func4 = std::bind(func3, 456);
    func4();
    {
        Object instance;
        // bind( 클래스 멤버 함수 포인터, 클래스 인스턴스 포인터, 파라미터 개수 지정(1~10))
        auto f = std::bind(&Object::hello, &instance, std::placeholders::_1);
        f(string("World"));
        // bind( 함수 포인터, 파라미터 개수 지정)
        auto f2 = std::bind(&goodbye, std::placeholders::_1);
        f2(string("World"));
    }
    return 0;
}출력 결과
Hello, World!
Hello, World!
JackJack
sudo
1
2
1
2
10
123
456
Hello World
Goodbye World728x90
    
    
  'C++ > 따배C++ 19강 모던 C++ 기능들' 카테고리의 다른 글
| [C++/CPP] 19.06. multi-threading Example inner product 벡터 내적을 통한 멀티 쓰레딩 예제 (0) | 2021.12.16 | 
|---|---|
| [C++/CPP] 19.05 Task base, async, future, promise 사용법 (0) | 2021.12.15 | 
| [C++/CPP] 19.04 Race Condition and std::atomic, std::scoped_lock (0) | 2021.12.12 | 
| [C++/CPP] 19.03 std::thread와 멀티 쓰레딩 기초 (0) | 2021.12.12 | 
| [C++/CPP] 19.02 여러개 값 반환 함수, multi return function (0) | 2021.12.11 |