1
将一个类的成员函数传递给另一个类的std::function
的正确方法是什么?将对象的函数传递给另一个类的另一个std ::函数
例如,下面的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*)>}')**