std::function used with std::bind
suggest changestd::function can store a callback with a fixed signature. A lambda is usually clearer than std::bind for adapting a member function. The sample below uses a lambda; std::bind with std::function is shown in std::function with lambda and std::bind:
#include <functional>
#include <iostream>
#include <string>
class EventSource {
public:
std::function<void(int, const std::string&)> callback;
void fire() {
if (callback) {
callback(100, "event fired");
}
}
};
class EventHandler {
public:
EventHandler() {
source_.callback = [this](int value, const std::string& message) {
handle_event(value, message);
};
}
void run() {
source_.fire();
}
private:
void handle_event(int value, const std::string& message) {
std::cout << message << ": " << value << '\n';
}
EventSource source_;
};
int main() {
EventHandler handler;
handler.run();
}
The lambda captures this, so it must not be invoked after the EventHandler has been destroyed. Longer-lived or asynchronous callbacks need an explicit lifetime strategy, often based on std::weak_ptr.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents