[英]how to create wrapper around std::bind
I have a function object typedef std::function<bool(Event*)> Handler
.我有一个函数对象
typedef std::function<bool(Event*)> Handler
。 A member function always gets assigned to this object.成员函数总是被分配给这个对象。 So, I am using
std::bind
to achieve that.所以,我使用
std::bind
来实现这一点。
Handler f = std::bind(&LevelSystem::switchLevel, this, std::placeholders::_1);
f(new Event("test"));
This code above works as expected, but I want to wrap the std::bind
in a helper function for cleaner code.上面的代码按预期工作,但我想将
std::bind
包装在辅助函数中以获得更清晰的代码。 This is what I have come up with.这是我想出的。
template<class Func> inline Handler MemFn(Func &&f) {
return std::bind(f, this, std::placeholders::_1);
}
And the usage will be:用法将是:
Handler f = MemFn(&LevelSystem::switchLevel);
I am getting an error when using this function:使用此功能时出现错误:
No viable conversion from
'__bind<bool(LevelSystem::*&)(Event *), System *,std::__1::placeholders::__ph<1> &>' to
'Handler' (aka 'function<bool(Event *)>')
I do not understand the error.我不明白这个错误。
You're trying to create a bind expression that will call a bool (LevelSystem::*)(Event*)
function on a System
object, which is not possible.您正在尝试创建一个绑定表达式,该表达式将在
System
对象上调用bool (LevelSystem::*)(Event*)
函数,这是不可能的。
You need to bind the correct dynamic type of this
to the function, as your comment indicates you've now done by passing the this
pointer to MemFn
.您需要将
this
的正确动态类型绑定到函数,因为您的注释表明您现在已经通过将this
指针传递给MemFn
来MemFn
。
If you're always going to pass a pointer-to-member-function to MemFn
then there's no point passing it by rvalue-reference, you might as well just pass the pointer-to-member.如果您总是要将指向成员函数的指针传递给
MemFn
那么通过右值引用传递它是没有意义的,您不妨只传递指向成员的指针。 Doing that allows you to deduce the class type, so you can then cast this
to that type:这样做,可以让你推断类的类型,所以你可以再投
this
该类型:
template<typename Ret, typename Class, typename Param>
inline Handler MemFn(Ret (Class::*f)(Param)) {
return std::bind(f, static_cast<Class*>(this), std::placeholders::_1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.