如何在std :: bind周围创建包装器

Gas*_*sim 1 c++ function-pointers c++11

我有一个功能对象typedef std::function<bool(Event*)> Handler.成员函数始终分配给此对象.所以,我正在用它std::bind来实现这一目标.

Handler f = std::bind(&LevelSystem::switchLevel, this, std::placeholders::_1);
f(new Event("test"));
Run Code Online (Sandbox Code Playgroud)

上面的代码按预期工作,但我想std::bind在一个帮助函数中包含更干净的代码.这就是我想出的.

 template<class Func> inline Handler MemFn(Func &&f) {
     return std::bind(f, this, std::placeholders::_1);
  }
Run Code Online (Sandbox Code Playgroud)

用法将是:

 Handler f = MemFn(&LevelSystem::switchLevel);
Run Code Online (Sandbox Code Playgroud)

使用此功能时出错:

No viable conversion from
'__bind<bool(LevelSystem::*&)(Event *), System *,std::__1::placeholders::__ph<1> &>' to
'Handler' (aka 'function<bool(Event *)>')
Run Code Online (Sandbox Code Playgroud)

我不明白这个错误.

Jon*_*ely 6

您正在尝试创建一个将bool (LevelSystem::*)(Event*)System对象上调用函数的绑定表达式,这是不可能的.

您需要将正确的动态类型绑定this到函数,因为您的注释表明您现在通过将this指针传递给您来完成MemFn.

如果你总是要将指向成员函数的函数MemFn传递给那时没有通过rvalue-reference传递它的点,那么你也可以将指针传递给成员.这样做可以推断出类类型,因此可以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);
  }
Run Code Online (Sandbox Code Playgroud)