如何使用 std::bind with lambda

How to use std::bind with lambda

本文关键字:with lambda bind std 何使用      更新时间:2023-10-16

我正在尝试在我的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

但我只看到"绑定尝试"。 我很确定 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);