C++11 lambda as member variable?

后端 未结 5 1233
Happy的楠姐
Happy的楠姐 2021-01-31 07:24

Can lambda\'s be defined as class members?

For example, would it be possible to rewrite the code sample below using a lambda instead of a function object?



        
5条回答
  •  悲&欢浪女
    2021-01-31 08:11

    #include 
    
    struct Foo {
        std::function bar;
    };
    
    void hello(const std::string & name) {
        std::cout << "Hello " << name << "!" << std::endl;
    }
    
    int test_foo() {
        Foo f;
        f.bar = std::bind(hello, "John");
    
        // Alternatively: 
        f.bar = []() { hello("John"); };
        f.bar();
    }
    

提交回复
热议问题