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
1 2 3 4 5 6 7 8 9 10 |
|
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
If the callback is a free-standing function without a class context, std::bind is not required.
1 2 3 4 5 6 7 8 9 10 |
|
For anonymous callbacks, lambda functions can be used with the event handler.
1 |
|
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!