如何使用 std::bind 和 lambda

How to use std::bind with lambda

我正在尝试在我的 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();    
}

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

bind attempt
say hello

但我只看到 "bind attempt"。我很确定我对 lambda 有一些不理解的地方。

std::bind(&Foo::func, this, input);

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

你可以使用

auto f = std::bind(&Foo::func, this, input);
f();

std::bind(&Foo::func, this, input)();

但在这种情况下,为什么不直接写成简单的方式呢?

this->func(input);