I have a function object typedef std::function<bool(Event*)> Handler
. A member function always gets assigned to this object. So, I am using std::bind
to achieve that.
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. 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.
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
.
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. Doing that allows you to deduce the class type, so you can then cast this
to that type:
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);
}