在一个类中使用带成员函数的通用std :: function对象 [英] Using generic std::function objects with member functions in one class
问题描述
对于一个类,我想在同一个类的成员函数中存储一些函数指针 map
存储 std :: function
对象。但是我在这段代码的开头失败了:
For one class I want to store some function pointers to member functions of the same class in one map
storing std::function
objects. But I fail right at the beginning with this code:
class Foo {
public:
void doSomething() {}
void bindFunction() {
// ERROR
std::function<void(void)> f = &Foo::doSomething;
}
};
我收到错误C2064:term不会计算为一个函数,
在
xxcallobj
加上一些奇怪的模板实例化错误。目前我在Windows 8与Visual Studio 2010/2011和Win 7与VS10的工作失败了。该错误必须基于一些奇怪的C ++规则,我不遵循。
I receive error C2064: term does not evaluate to a function taking 0 arguments
in xxcallobj
combined with some weird template instantiation errors. Currently I am working on Windows 8 with Visual Studio 2010/2011 and on Win 7 with VS10 it fails too. The error must be based on some weird C++ rules i do not follow.
编辑:我做不使用boost。这是C ++ 11集成在MS编译器中。
I do NOT use boost. This is C++11 integrated in the MS compiler.
推荐答案
非静态成员函数必须用对象调用。也就是说,它总是隐式传递this指针作为其参数。
A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.
因为你的 std :: function
指定您的函数不接受任何参数(< void(void)>
),必须绑定 )参数。
Because your std::function
signature specifies that your function doesn't take any arguments (<void(void)>
), you must bind the first (and the only) argument.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
如果要使用参数绑定函数,则需要指定占位符:
If you want to bind a function with parameters, you need to specify placeholders:
using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, _1, _2);
或者,如果你的编译器支持C ++ 11 lambdas:
Or, if your compiler supports C++11 lambdas:
std::function<void(int,int)> f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}
(我手头没有C ++ 11编译器现在,所以我不能检查这一个。)
(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)
这篇关于在一个类中使用带成员函数的通用std :: function对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!