Wednesday, May 3, 2023

C++ Event Dispatching


In C++, event dispatching is typically done through a loop that continually checks for new events and dispatches them to their appropriate handlers. Here's an example of how you might use a simple event loop to dispatch events in a C++ program:

#include <iostream> #include <vector> // Define a simple event type struct Event { int type; int data; }; // Define an event handler function void handleEvent(Event event) { std::cout << "Event type " << event.type << " received with data " << event.data << std::endl; } int main() { // Define a vector to hold events std::vector<Event> eventQueue; // Add some events to the queue eventQueue.push_back({ 1, 42 }); eventQueue.push_back({ 2, 123 }); // Event loop while (!eventQueue.empty()) { // Get the next event from the queue Event event = eventQueue.front(); eventQueue.erase(eventQueue.begin()); // Dispatch the event to its appropriate handler switch (event.type) { case 1: handleEvent(event); break; case 2: handleEvent(event); break; default: std::cerr << "Unknown event type " << event.type << std::endl; break; } } return 0; }

In this example, we define a simple Event struct that has a type and data field. We also define a handleEvent function that takes an Event as its argument and simply prints out some information about it.

We then create a vector to hold some events, add a couple of events to the vector, and start our event loop. In the event loop, we retrieve the next event from the queue and dispatch it to its appropriate handler using a switch statement. Finally, we exit the event loop when there are no more events in the queue.

Note that this is a very simple example, and in practice, event dispatching can become much more complex depending on the requirements of your program. For example, you might need to implement more sophisticated event queuing mechanisms, such as priority queues or event channels. Additionally, you might need to handle events in multiple threads or across multiple processes.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...