I'm trying to write a really simple event or message class in C++. I want the event to hold the time of occurrence and some data which are specific to the event type. What I have at the moment is the following
class EventData{
public:
virtual ~EventData(void) = 0;
};
struct Event{
Event(EventType type, Time time, EventData *data = nullptr):
type_(type), time_(time), data_(data)
{}
~Event(void){
if(data_) delete data_;
}
//Disable copying, event memory will be managed by EventManager
Event(const Event& other) = delete;
const EventType type_;
const Time time_;
const EventData *data_;
};
In my main loop, I have something like this,
bool running = true;
while(running){
const Event* nextEvent = evtManager.getNextEvent();
switch(nextEvent.type_){
case EVT_A:
const EventAData* data = static_cast<EventAData*>(nextEvent.data_);
//do stuff
break;
}
...
case EVT_END:
running = false;
break;
}
}
The question then is if there is a more efficient way of doing this, i.e. with templates. the other problem is that someone could accidentally give the wrong EventType
, EventData
pair, in which case the static_cast
will fail.
I should note that I want this Event
class to be as fast as possible, especially the access to the time_
member variable.