Store Function Pointers to any Member Function

前端 未结 4 1549
太阳男子
太阳男子 2020-12-30 16:59

My Event Manager

For a event manager I need to store many pointers to functions in a vector to call them when the event is triggered. (I will provide the source co

4条回答
  •  误落风尘
    2020-12-30 17:22

    This is the typical case where you should use polymorphism instead of function (or member function) pointers.

    As you noted, your component classes should inherit from a common class Component, which contains virtual method(s) representing the event(s):

    class Component
    {
    public:
        virtual void OnPlayerLevelUp()
        {
        }
    };
    
    class ComponentSound : public Component
    {
    public:
         // override it
        void OnPlayerLevelUp()
        {
            // do the actual work
        }
    };
    

    Your ListEvent type will now look like this:

    typedef unordered_map> ListEvent;
    

    As for the optional void* paramenter in event methods, you can specify it as an optional parameter, but the fact that it's a void* is a bad sign (use of void* can lead to loss of type safety), so I would suggest that you look for a different way to achieve what you want.

提交回复
热议问题