如何将 std::bind 与 lambda 一起使用

pet*_*nic 1 c++ lambda std stdbind c++11

我正在尝试在我的 lambda 中使用 std::bind :

#include <functional>
#include <iostream>
#include <string>

struct Foo {
    Foo() {}
    void func(std::string input)
    {
        std::cout << input << '\n';
    }

    void bind()
    {
        std::cout << "bind attempt" << '\n';
        auto f_sayHello = [this](std::string input) {std::bind(&Foo::func, this, input);};
        f_sayHello("say hello");
    }
};

int main()
{
    Foo foo;
    foo.bind();    
}
Run Code Online (Sandbox Code Playgroud)

当我运行这段代码时,我所期望的是看到以下输出

bind attempt
say hello
Run Code Online (Sandbox Code Playgroud)

但我只看到“绑定尝试”。我很确定 lambda 有一些我不明白的地方。

use*_*751 5

std::bind(&Foo::func, this, input);
Run Code Online (Sandbox Code Playgroud)

std::bind将创建一个调用的函子this->func(input);。但是,std::bind不调用this->func(input);自身。

你可以使用

auto f = std::bind(&Foo::func, this, input);
f();
Run Code Online (Sandbox Code Playgroud)

或者

std::bind(&Foo::func, this, input)();
Run Code Online (Sandbox Code Playgroud)

但既然如此,为什么不直接写成简单的方式呢?

this->func(input);
Run Code Online (Sandbox Code Playgroud)