The original question aimed to create a generic event-handling mechanism that would work consistently across different classes. Instead of relying on static methods and passing around class instance pointers, a more modern C approach can be employed using std::function and std::bind.
The event handler class now accepts a std::function object as an argument. A function object represents a callable entity that can be passed around like a regular function pointer. The event handler method addHandler takes a std::function
class EventHandler { public: void addHandler(std::functioncallback) { cout Binding Specific Functions
To bind a specific class method to the event handler, std::bind is used. std::bind specifies the this pointer and the function to be called when the event is triggered.
class MyClass { public: MyClass(); // Note: No longer marked `static`, and only takes the actual argument void Callback(int x); private: int private_x; }; MyClass::MyClass() { using namespace std::placeholders; // for `_1` private_x = 5; handler->addHandler(std::bind(&MyClass::Callback, this, _1)); } void MyClass::Callback(int x) { // No longer needs an explicit `instance` argument, // as `this` is set up properly coutFree-Standing Functions and Lambda Functions
If the callback is a free-standing function without a class context, std::bind is not required.
void freeStandingCallback(int x) { // ... } int main() { // ... handler->addHandler(freeStandingCallback); }For anonymous callbacks, lambda functions can be used with the event handler.
handler->addHandler([](int x) { std::coutIn this way, using std::function and std::bind provides a flexible and generic solution for callbacks that can be applied to different classes and functions.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3