templates - Writing a very simple event class in C++ -
i'm trying write simple event or message class in c++. want event hold time of occurrence , data specific event type. have @ moment 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 managed eventmanager event(const event& other) = delete; const eventtype type_; const time time_; const eventdata *data_; };
in main loop, have 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 if there more efficient way of doing this, i.e. templates. other problem accidentally give wrong eventtype
, eventdata
pair, in case static_cast
fail.
i should note want event
class fast possible, access time_
member variable.
- there no need check whether pointer null before deleting it.
- you trying perform type-erasing, , perform different tasks depending on type erased. it's inefficient. boost::variant instead, seems it's need.
- if insist on using method, should use
typeid
discriminate between types.
Comments
Post a Comment