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::function<void(int)> callback) { cout << "Handler added..." << endl; // Let's pretend an event just occured callback(1); } };
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 cout << x + private_x << endl; }
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::cout << "x is " << x << '\n'; });
In 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.
The above is the detailed content of How to Implement Generic C Callbacks Using Class Members and `std::function`?. For more information, please follow other related articles on the PHP Chinese website!