vendredi 16 août 2019

Passing a child class as a parameter to a function which takes the parent class

I had a hard time writing the title for this problem since it is so specific. Essentially I am making a program that can handle many events and to do so I have created some event structs for several different types of events. If you look at the code below what I have done is I have also created a typedef for a function that handles the events called a Listener. Essentially my class handles the event and runs any user defined listeners that exist. However to clean up my code I have the listeners take an Event* instead of a specific one like a MouseEvent*. The problem with this is that when the user tries to make a function using the Event* they can only access they type even though it is passed a MouseEvent* with all the data. Please let me know if more info is required to help :)

Is there anyway to fix this without making the user do a... MouseEvent* newEvent = dynamic_cast<MouseEvent*>(event);

Structure

struct Event {
    EventType type;
};
struct MouseEvent : Event {
    int x;
    int y;
    bool down;
    uint8_t which;
};
typedef function<void(MYCLASS*, Event*)> Listener;
typedef vector<Listener> Listeners;

Event Handler

void MYCLASS::eventHandler(Event* event, Listeners* listeners) {
  for(auto it = listeners->begin(); it != listeners->end(); ++it) {
    (*it)(this,event);
  }
}

Example User Defined Listener

myclassinstance.addListener(MOUSEMOVE, [&](MYCLASS* a, Event* e) {
     //some code (would like to access data from actual event instead of just type
});

Aucun commentaire:

Enregistrer un commentaire