对于一个类,我想在一个存储 std::function
对象的 map
中存储一些指向同一类的成员函数的函数指针。但我一开始就用这段代码失败了:
#include <functional>
class Foo {
public:
void doSomething() {}
void bindFunction() {
// ERROR
std::function<void(void)> f = &Foo::doSomething;
}
};
我收到 error C2064: term doesn't evaluate to a functiontaking 0 arguments
in xxcallobj
以及一些奇怪的模板实例化错误。目前,我正在使用 Visual Studio 2010/2011 使用 Windows 8,使用 VS10 使用 Win 7,它也失败了。该错误必须基于我不遵循的一些奇怪的 C++ 规则
最佳答案
必须使用对象调用非静态成员函数。也就是说,它总是隐式传递“this”指针作为参数。
因为你的 std::function
签名指定您的函数不接受任何参数 (<void(void)>
),您必须绑定(bind)第一个(也是唯一的)参数。
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
如果要绑定(bind)带参数的函数,需要指定占位符:
using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
或者,如果您的编译器支持 C++11 lambda:
std::function<void(int,int)> f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}
(我手头没有支持 C++11 的编译器现在,所以我无法检查这个。)
关于c++ - 在一个类中使用具有成员函数的通用 std::function 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582546/