It's been a few years since I did anything with C++. I'm going to read and review some books. In the meantime I need to know if there's any apparent problems with this code, Meaning stack vs heap allocation, function pointer, stl map/vector/pair, etc. For instance I couldn't get associative arrays working so I quickly threw in "->find(event)->second->" instead of "[event]->", and "this->Events->insert" instead of "this->Events[event] =".
Please don't mind my syntax.
Yeah....... o.o
Thanks in advanceCode:#include <map> #include <vector> #include <string> #include <iostream> #include <utility> class EventDispatcher { public: std::map<std::string, std::vector<void (*)()>* >* Events; public: EventDispatcher(); public: virtual ~EventDispatcher() {} public: void AddEvent(const char*); public: void RemoveEvent(const char*); public: void DispatchEvent(const char*); public: void AddEventListener(const char*, void (*)()); public: void RemoveEventListener(const char*, void (*)()); public: bool EventExists(const char*); public: void Clear(); public: bool Empty(); }; void callback() { std::cout << "Called" << std::endl; } int main() { EventDispatcher* eventDispatcher = new EventDispatcher(); eventDispatcher->AddEvent("a"); eventDispatcher->AddEvent("b"); eventDispatcher->AddEvent("c"); eventDispatcher->AddEventListener("b", &callback); //eventDispatcher->RemoveEventListener("b", &callback); eventDispatcher->DispatchEvent("b"); std::cin.get(); } EventDispatcher::EventDispatcher() { this->Events = new std::map<std::string, std::vector<void (*)()>* >(); } void EventDispatcher::AddEvent(const char* event) { this->Events->insert(std::pair<std::string, std::vector<void (*)()>* >(std::string(event), new std::vector<void (*)()>())); } void EventDispatcher::RemoveEvent(const char* event) { if(this->EventExists(event)) this->Events->erase(event); } bool EventDispatcher::Empty() { return this->Events->empty(); } void EventDispatcher::Clear() { if(!this->Empty()) this->Events->clear(); } /** * Usage: eventDispatcher.AddEventListener("eventName", &func); */ void EventDispatcher::AddEventListener(const char* event, void (*listener)()) { if(!this->EventExists(event)) this->AddEvent(event); this->Events->find(event)->second->push_back(listener); } bool EventDispatcher::EventExists(const char* event) { return this->Events->find(event) != this->Events->end(); } void EventDispatcher::RemoveEventListener(const char* event, void (*listener)()) { if(this->EventExists(event)) for(std::vector<void(*)()>::iterator i = this->Events->find(event)->second->begin(), l = this->Events->find(event)->second->end(); i != l; i++) if((*i) == listener) this->Events->find(event)->second->erase(i); } void EventDispatcher::DispatchEvent(const char* event) { for(std::vector<void(*)()>::iterator i = this->Events->find(event)->second->begin(), l = this->Events->find(event)->second->end(); i != l; i++) (*(*i))(); }



LinkBack URL
About LinkBacks






