【问题标题】:Use std::bind and store into a std:: function使用 std::bind 并存储到 std:: 函数中
【发布时间】:2020-10-03 06:42:14
【问题描述】:

我正在尝试使用 std::bind 绑定到函数并将其存储到我的 std::function 回调对象中。我写的代码是我实际代码的简化版本。下面的代码不能编译,说

_1 未在范围内声明

注意:我知道使用 lambda 也可以做到这一点。但是函数处理程序已经存在并且需要使用,否则我需要在 lambda 中调用处理程序。

#include <iostream>
#include <functional>

typedef std:: function<void(int)> Callback;

template <class T>
class Add
{
public:
    Add(Callback c)
    {
        callback = c;
    }
    void add(T a, T b)
    {
        callback(a+b);
    }

private:
    Callback callback;
};

void handler(int res)
{
    printf("result = %d\n", res);
}

int main(void) 
{
    // create a callback
    // I know it can be done using lambda
    // but I want to use bind to handler here 
    Callback c = std::bind(handler, _1);
    
    /*Callback c = [](int res)
    {
        printf("res = %d\n", res);
    };*/
    
    // create template object with 
    // the callback object
    Add<int> a(c);
    a.add(10,20);
}

【问题讨论】:

  • _1 位于 std::placeholders 命名空间而非全局命名空间中
  • 我仍在试图弄清楚为什么你要使用一种不如另一种的技术,lamdas 与个人风格无关,它只是建议的东西,在很多情况下它更快绑定lamda vs bind
  • 我知道。实际上这个函数是一个遗留函数,所以我想只是将它绑定到回调。

标签: c++ std-function stdbind


【解决方案1】:

占位符_1_2_3...被放置在命名空间std::placeholders中,你应该像这样限定它

Callback c = std::bind(handler, std::placeholders::_1);

或者

using namespace std::placeholders;
Callback c = std::bind(handler, _1);

【讨论】:

    【解决方案2】:

    占位符位于 std 命名空间中自己的命名空间中。 添加using namespace std::placeholders或使用std::placeholders::_1

    很好的例子:std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 2023-03-16
      • 2015-07-14
      • 1970-01-01
      相关资源
      最近更新 更多