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*)>}')**