【问题标题】:How to use std::bind with lambda如何将 std::bind 与 lambda 一起使用
【发布时间】:2016-01-18 20:20:00
【问题描述】:

我正在尝试在我的 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(&amp;Foo::func, this, input)(); ?
  • @PiotrSkotnicki 哇,快速有效的答案。谢谢

标签: c++ c++11 lambda std stdbind


【解决方案1】:
std::bind(&Foo::func, this, input);

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

你可以使用

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

或

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

但是在这种情况下,为什么不简单地写呢?

this->func(input);

【讨论】:

  • 我需要将 std::function 传递给 3rdParty,这就是原因。所以,我在为我玩这个新概念,试图理解。谢谢你的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2012-10-28
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 2016-10-04
相关资源
最近更新 更多