2

What is the right way to pass a member function of one class to an std::function of another class?

For example, the Bar below wants to store one function of a Foo object.

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;
}

This doesn't compile:

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*)>}')**
Praetorian
  • 106,671
  • 19
  • 240
  • 328
Solti
  • 633
  • 2
  • 6
  • 17

2 Answers2

4

Foo::isEven takes an argument which you'll be passing later, so you need to add a placeholder to indicate that unbound argument.

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

Or just use a lambda instead of bind

bar.testFunction = [&foo1](int x) { return foo1.isEven(x); };
Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

You can use a lambda:

bar.testFunction = [&foo1](int x){ return foo1.isEven(x); };
6502
  • 112,025
  • 15
  • 165
  • 265