如何在Visual Studio 11中直接将成员函数绑定到std ::函数? [英] How to directly bind a member function to an std::function in Visual Studio 11?
问题描述
我可以很容易地将成员函数绑定到一个 std :: function
,通过用一个带有capture子句的lambda表达式包装。
I can easily bind member functions to a std::function
by wrapping them with a lambda expression with capture clause.
class Class
{
Class()
{
Register([=](int n){ Function(n); });
}
void Register(std::function<void(int)> Callback)
{
}
void Function(int Number)
{
}
};
但我想直接绑定它们,像下面这样。
But I want to bind them directly, something like the following.
// ...
Register(&Class::Function);
// ...
我认为根据C ++ 11标准,应该支持。但是,在Visual Studio 11中,我得到这些编译器错误。
I think according to the C++11 standard, this should be supported. However, in Visual Studio 11 I get these compiler errors.
错误C2440:'newline':无法从'int' *'
error C2440: 'newline' : cannot convert from 'int' to 'Class *'
错误C2647:'。*':不能在'int'上解引用'void(__thiscall Class :: *
error C2647: '.*' : cannot dereference a 'void (__thiscall Class::* )(int)' on a 'int'
推荐答案
我认为根据C ++ 11标准,支持
I think according to the C++11 standard, this should be supported
不是真的,因为非静态成员函数有一个类型为(cv-qualified)的隐式第一个参数 YourType *
,因此在这种情况下它不匹配 void(int)
。因此需要 std :: bind
:
Not really, because a non-static member function has an implicit first parameter of type (cv-qualified) YourType*
, so in this case it does not match void(int)
. Hence the need for std::bind
:
Register(std::bind(&Class::Function, PointerToSomeInstanceOfClass, _1));
例如
Class c;
using namespace std::placeholders; // for _1, _2 etc.
c.Register(std::bind(&Class::Function, &c, _1));
编辑您提到这是用相同的 Class
实例。在这种情况下,你可以使用一个简单的非成员函数:
Edit You mention that this is to be called with the same Class
instance. In that case, you can use a simple non-member function:
void (int n) foo
{
theClassInstance.Function(n);
}
然后
Class c;
c.Register(foo);
这篇关于如何在Visual Studio 11中直接将成员函数绑定到std ::函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!