Ok so I have created a system that listens and handles events as shown below. I created an Event struct and several more specific structs to hold event data. I also created a typedef for a Listener which takes in event data. An internal event handler receives the events and runs all of the user defined listeners in the appropriate vector for that event. However the specific event data is sliced off since the Event class only contains the EventType. Is there any way around this so that I do not have to rewrite almost all of my code. I have tried passing the event by reference but that didn't solve it. Here is the code so far...
EDIT: I am aware that I can use a static_cast to use the other data in the event however since I am trying to create a simple API for developers I would like to not force the user to static_cast in every listener.
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;
Handler
void MYCLASS::eventHandler(Event& event, Listeners* listeners) {
for(auto it = listeners->begin(); it != listeners->end(); ++it) {
(**it)(*this,event);
}
}
Example user defined listener
instance.addListener(MOUSEMOVE, [](MYCLASS& a, Event& e) {
cout << e.x << endl; //THIS LINE DOES NOT WORK
});