简体   繁体   中英

Create a non-constant pointer to member function for SDL event filtering

I'm playing with SDL, and I am trying to supply a function pointer to an event filter. This works fine if I make the function a static member of ObjectWithState , but I'd like to have the callback function alter the state of the object. I was hoping to do this perhaps using a functor, but I can't quite work it out.

Is there any C++11 trickery that I can use to make this work?

class ObjectWithState
{
    int someState;

public:    
    int operator()(void* userData, SDL_Event *event)
    {
        return ++someState;
    }
};


int main()
{
    //boilerplate
    ObjectWithState obj;

    SDL_EventFilter f = &(obj.operator()); //ERROR -> cannot create non-constant pointer to member function
    SDL_SetEventFilter( f, nullptr );
}

Use the userdata parameter to point to your object, and dispatch through a static method to the non-static method:

class ObjectWithState
{
    int someState;

public:    
    int operator()(SDL_Event *event)
    {
        ++someState
    }

    static int dispatch(void* userdata, SDL_Event* event)
    {
        return static_cast<ObjectWithState*>(userdata)->operator()(event);
    }
};


int main()
{
    //boilerplate
    ObjectWithState obj;

    SDL_SetEventFilter(&ObjectWithState::dispatch, &obj);
}

You can't assign pointer to member functions to C style function pointers. You have to use a free function or a static function, and then call whatever members you need inside that.

Actually, std::bind may allow you to do it. Not entirely sure though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM