C++ Event Mechanism Implementation Guide
Implementing event mechanisms in C++ typically requires the use of callback functions or the observer pattern. Here is a simple implementation method:
- Callback function: Define an event class that includes a pointer to a callback function. When the event occurs, call the callback function to handle the event. Example code is as follows:
#include <iostream>
#include <functional>
class Event {
public:
using Callback = std::function<void()>;
Event(Callback callback) : m_callback(callback) {}
void trigger() {
if (m_callback) {
m_callback();
}
}
private:
Callback m_callback;
};
void handleEvent() {
std::cout << "Event handled" << std::endl;
}
int main() {
Event event(handleEvent);
event.trigger();
return 0;
}
- Observer pattern: defines a subject class and an observer class, the subject class contains methods to register observers and notify observers. Sample code is as follows:
#include <iostream>
#include <vector>
class Observer {
public:
virtual void update() = 0;
};
class Subject {
public:
void addObserver(Observer* observer) {
m_observers.push_back(observer);
}
void notifyObservers() {
for (Observer* observer : m_observers) {
observer->update();
}
}
private:
std::vector<Observer*> m_observers;
};
class EventObserver : public Observer {
public:
void update() override {
std::cout << "Event handled" << std::endl;
}
};
int main() {
Subject subject;
EventObserver eventObserver;
subject.addObserver(&eventObserver);
subject.notifyObservers();
return 0;
}
The above are two simple methods to implement event mechanisms, developers can choose the appropriate method based on their specific requirements during actual development.