简体   繁体   English

创建指向成员函数的非恒定指针以进行SDL事件过滤

[英]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. 我正在使用SDL,并且试图提供指向事件过滤器的函数指针。 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. 如果将函数ObjectWithState的静态成员,则此方法ObjectWithState ,但我希望回调函数更改对象的状态。 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? 我可以使用任何C ++ 11技巧来实现此目的吗?

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: 使用userdata参数指向您的对象,并通过静态方法将其分配给非静态方法:

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. 您不能将指向成员函数的指针分配给C样式函数指针。 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. 实际上, std::bind可能允许您执行此操作。 Not entirely sure though. 虽然不完全确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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