【问题标题】:pass a function of an object to another std::function of another class将对象的函数传递给另一个类的另一个 std::function
【发布时间】:2016-03-16 22:18:26
【问题描述】:

将一个类的成员函数传递给另一个类的std::function 的正确方法是什么?

例如,下面的Bar 想要存储Foo 对象的一个​​函数。

class Foo {
public:
  Foo(int x) : data(x) {}
  bool isEven(int y) { return (data + y) & 0x01; }
  int data;
};

class Bar {
public:
  std::function<bool(int)> testFunction;
};


int main() {
  Foo foo1(1);
  Bar bar;
  bar.testFunction = std::bind(&Foo::isEven, &foo1);
  if (bar.testFunction(3)) {
    std::cout << "is even" << std::endl;
  }
  return 0;
}

这不会编译:

no match for 'operator=' (operand types are 'std::function<bool(int)>' and 'std::_Bind_helper<false, bool (Foo::*)(int), Foo*>::type {aka std::_Bind<std::_Mem_fn<bool (Foo::*)(int)>(Foo*)>}')**

【问题讨论】:

    标签: c++ c++11 std-function stdbind


    【解决方案1】:

    Foo::isEven 接受您稍后将传递的参数,因此您需要添加一个占位符来指示该未绑定参数。

    bar.testFunction = std::bind(&Foo::isEven, &foo1, std::placeholders::_1);
    

    或者只使用 lambda 而不是 bind

    bar.testFunction = [&foo1](int x) { return foo1.isEven(x); };
    

    【讨论】:

      【解决方案2】:

      您可以使用 lambda:

      bar.testFunction = [&foo1](int x){ return foo1.isEven(x); };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 1970-01-01
        • 1970-01-01
        • 2019-03-09
        • 1970-01-01
        • 1970-01-01
        • 2015-09-15
        相关资源
        最近更新 更多