2016-05-30 13 views
1

Ich möchte ein Array von OIS :: Keys (int) und von std :: function.Wie kann ich eine Memberfunktion an eine std :: -Funktion binden?

Ich habe dies:

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) 
    }, 
}; 

Aber wenn ich versuche, das ich diesen Compiler-Fehler haben zu kompilieren:

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) 
          ^

Was habe ich falsch gemacht?

+3

vielleicht 'std :: bind (& Userinput :: selectBazooka, & input, std :: placeholders :: _ 1, std :: platzhalter :: _ 2) ' –

+3

Gibt es einen Grund, warum du keinen Lambda verwendest? (Imo macht es den Code klarer als binden) – Borgleader

+1

PiotrSkotnicki thansk, das funktioniert gut! @Borgleader Wie könnte ein Lambda hier nützlich sein? –

Antwort

5

Das erste Argument von std::bind ist ein aufrufbares Objekt. In Ihrem Fall sollte das &UserInput::selectBazooka sein. Das Objekt, das einem Aufruf dieser Elementfunktion zugeordnet werden soll (&input), wird anschließend ausgeführt (Sie haben diese Reihenfolge umgekehrt). Dennoch müssen Sie Platzhalter für die fehlenden Parameter verwenden:

std::bind(&UserInput::selectBazooka, &input, std::placeholders::_1, std::placeholders::_2) 
6

einen Lambda-Verwendung, so sein würde (statt std::bind())

[&](Worms*x, const Ogre::FrameEvent&y) { return input.selectBazooka(x,y); } 
Verwandte Themen