如何将成员函数绑定到std :: function?

Dim*_*lov 1 c++ stl c++11

我想做一个OIS :: Keys(int)和std :: function的数组.

我有这个 :

struct UserCommands
{
  OIS::KeyCode key;
  std::function<bool(Worms *, const Ogre::FrameEvent& evt)> func;
};

UserInput input;

UserCommands usrCommands[] =
{
  {
    OIS::KC_A, std::bind(&input, &UserInput::selectBazooka)
  },
};
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译它时,我有这个编译错误:

    In file included from includes/WormsApp.hh:5:0,
                     /src/main.cpp:2:
/includes/InputListener.hh:26:25: error: could not convert ‘std::bind(_Func&&, _BoundArgs&& ...) [with _Func = UserInput*; _BoundArgs = {bool (UserInput::*)(Worms*, const Ogre::FrameEvent&)}; typename std::_Bind_helper<std::__is_socketlike<_Func>::value, _Func, _BoundArgs ...>::type = std::_Bind<UserInput*(bool (UserInput::*)(Worms*, const Ogre::FrameEvent&))>](&UserInput::selectBazooka)’ from ‘std::_Bind_helper<false, UserInput*, bool (UserInput::*)(Worms*, const Ogre::FrameEvent&)>::type {aka std::_Bind<UserInput*(bool (UserInput::*)(Worms*, const Ogre::FrameEvent&))>}’ to ‘std::function<bool(Worms*, const Ogre::FrameEvent&)>’
         OIS::KC_A, std::bind(&input, &UserInput::selectBazooka)
                             ^
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Wal*_*ter 6

使用lambda,就像这样(代替std::bind())

[&](Worms*x, const Ogre::FrameEvent&y) { return input.selectBazooka(x,y); }
Run Code Online (Sandbox Code Playgroud)


Pio*_*cki 5

第一个参数std::bind是可调用对象.在你的情况下,应该是&UserInput::selectBazooka.与该成员函数(&input)的调用相关联的对象随后发生(您颠倒了此顺序).但是,您必须使用占位符来显示缺少的参数:

std::bind(&UserInput::selectBazooka, &input, std::placeholders::_1, std::placeholders::_2)
Run Code Online (Sandbox Code Playgroud)