| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- // chatGPT-Event Dispatcher.cpp : This file contains the 'main' function. Program execution begins and ends there.
- //
- #include <iostream>
- #include <iostream>
- #include <functional>
- #include <vector>
- #include <algorithm>
- #include <map>
- #include <memory>
- #include <string>
- // EventType: unique identifier for event types
- using EventType = int;
- // Event base class
- class Event {
- public:
- explicit Event(EventType type) : type_(type) {}
- virtual ~Event() {}
- EventType GetType() const { return type_; }
- private:
- EventType type_;
- };
- // Example derived event with data
- class ButtonClickEvent : public Event {
- public:
- ButtonClickEvent(int buttonId, const std::string& label)
- : Event(1), buttonId_(buttonId), label_(label) {
- }
- int GetButtonId() const { return buttonId_; }
- const std::string& GetLabel() const { return label_; }
- private:
- int buttonId_;
- std::string label_;
- };
- // Event handler function: receives an Event pointer
- using EventHandler = std::function<void(const Event&)>;
- class EventDispatcher {
- public:
- // Connect a handler to an event type, returns a connection id
- size_t Connect(EventType type, EventHandler handler) {
- size_t id = ++last_id_;
- handlers_[type].push_back(std::make_pair(id, handler));
- return id;
- }
- // Disconnect a handler by id (for a specific event type)
- void Disconnect(EventType type, size_t id) {
- auto& vec = handlers_[type];
- vec.erase(std::remove_if(vec.begin(), vec.end(),
- [id](const std::pair<size_t, EventHandler>& pair) {
- return pair.first == id;
- }), vec.end());
- }
- // Emit (post) an event
- void Emit(const Event& evt) {
- auto it = handlers_.find(evt.GetType());
- if (it != handlers_.end()) {
- for (auto& pair : it->second) {
- pair.second(evt);
- }
- }
- }
- private:
- std::map<EventType, std::vector<std::pair<size_t, EventHandler>>> handlers_;
- size_t last_id_ = 0;
- };
- int main() {
- EventDispatcher dispatcher;
- // Connect a handler for ButtonClickEvent (event type 1)
- size_t conn = dispatcher.Connect(1, [](const Event& evt) {
- // Downcast to correct event type
- auto& clickEvt = static_cast<const ButtonClickEvent&>(evt);
- std::cout << "Button clicked! id=" << clickEvt.GetButtonId()
- << ", label=" << clickEvt.GetLabel() << std::endl;
- });
- // Emit a button click event
- ButtonClickEvent evt(42, "OK");
- dispatcher.Emit(evt);
- // Disconnect the handler
- dispatcher.Disconnect(1, conn);
- // Emit again (no output expected)
- dispatcher.Emit(evt);
- return 0;
- }
|