Home >Backend Development >C++ >How Can C 11's `std::function` and `std::bind` Solve Heterogeneous Class Callback Challenges?
Passing Callbacks Between Heterogeneous Classes
In C , defining callbacks that can be shared among various classes can pose a challenge. While providing a static member function and passing a pointer to the class instance is a common approach, it limits flexibility. Here's how to address this issue using C 11's std::function and std::bind:
Refactoring EventHandler
Instead of static methods and instance pointers, refactor EventHandler to accept std::function:
class EventHandler { public: void addHandler(std::function<void(int)> callback) { // ... (as above) } };
This function accepts a "function object" that takes an integer argument and returns nothing.
Adapting MyClass
Modify MyClass to remove the static keyword from Callback and provide an argument instead:
class MyClass { public: void Callback(int x); // ... }; MyClass::Callback(int x) { // ... (as above) }
To bind the Callback to the EventHandler, use std::bind:
handler->addHandler(std::bind(&MyClass::Callback, this, std::placeholders::_1));
The _1 placeholder represents the single argument.
Standalone Functions and Lambda Expressions
You can use standalone functions directly in addHandler:
void freeStandingCallback(int x) { // ... } handler->addHandler(freeStandingCallback);
Additionally, C 11 lambda expressions can be used within addHandler:
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
Conclusion
By employing std::function and std::bind, callbacks can be passed seamlessly between heterogeneous classes, providing flexibility and code reusability.
The above is the detailed content of How Can C 11's `std::function` and `std::bind` Solve Heterogeneous Class Callback Challenges?. For more information, please follow other related articles on the PHP Chinese website!