std::function used with std::bind

suggest change

std::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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents