문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top