C Callback Using Class Member for Multiple Classes
Problem:
In C , how can you create a generic callback function that works with multiple classes, each with its own callback member function?
Solution:
Originally, a static callback method and a pointer to the instance were used, but this approach can be improved. Here are two alternative solutions:
Using C 11 std::function and std::bind:
void addHandler(std::function<void(int)> callback);
std::bind(&MyClass::Callback, this, _1)
Using C 11 Lambda Functions:
With lambda functions, you can further simplify the code:
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
The above is the detailed content of How to Create Generic C Callbacks for Multiple Classes?. For more information, please follow other related articles on the PHP Chinese website!