【发布时间】: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