lundi 27 juin 2016

Member function pointer on derived class

I have some trouble with a member pointer in a CRTP template. Here the code it is a virtual call function who call a member function pointer on a crtp derived class.

class KeyboardHandler {
public:
    virtual void keyPressed(KeyboardKey) = 0;
    virtual void keyReleased(KeyboardKey) = 0;
    KeyboardHandler & operator=(const KeyboardHandler &) = default ;
};

template<class T>
class KeyboardHandlerOpti : public KeyboardHandler {
public:

    using KeyboardCallback = void (T::*)(KeyboardKey key, KeyboardStatus status) ;

KeyboardHandlerOpti(KeyboardCallback defaultCallback);

virtual void keyPressed(KeyboardKey key) override final;
virtual void keyReleased(KeyboardKey key) override final ;


std::vector<KeyboardCallback> mCallbackPressed ;
std::vector<KeyboardCallback> mCallbackReleased ;

KeyboardHandlerOpti & operator=(const KeyboardHandlerOpti &) = default ;

private:
    KeyboardCallback mDefaultCallback ;
};


class GlfwDefaultKeyboardHandler :
        public KeyboardHandlerOpti<GlfwDefaultKeyboardHandler> {
public:
    GlfwDefaultKeyboardHandler() ;

    GlfwDefaultKeyboardHandler & operator=(const GlfwDefaultKeyboardHandler &) = default ;

private:
    //This is type of KeyboardCallback
    void drawKey(KeyboardKey key, KeyboardStatus status) ;
} ;

The class GlfwDefaultKeyboardHandler is initialized with drawKey as KeyboardHandlerOpti::mDefaultCallback

template<class T>
KeyboardHandlerOpti<T>::KeyboardHandlerOpti(KeyboardCallback    defaultCallback) :
    mDefaultCallback(defaultCallback),
    mCallbackPressed(getKeyboardKeyCount(), mDefaultCallback),
    mCallbackReleased(getKeyboardKeyCount(), mDefaultCallback) {
}

and Callback are called with

template<class T>
void KeyboardHandlerOpti<T>::keyPressed(KeyboardKey key) {
    KeyboardCallback c = mCallbackPressed[getKeyValue(key)] ;
    (dynamic_cast<T *>(this)->*c)(key, KeyboardStatus::ePressed) ;
    //(this->*c)(key, KeyboardStatus::ePressed) ;
}

Unfortunately I have a segfault and I am not able to understand why. I found some interesting value in debug. I can see at the construction of KeyboardHandlerOpti that I have things that I don't really understand.

defaultCallback value is 0x4b7578 and debuger can tell the name of the function but mDefaultCallback is "0x7ef360, this adjustment 96" and it is the same value in both vectors.

So if someone can explain to me why do I have the segfault I would be very happy.

Aucun commentaire:

Enregistrer un commentaire