example4_callback_with_member_function.cpp

 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
26
27
28
29
#include <iostream>
#include <functional>

class MyClass {
public:
    void memberCallback(int result) const {
        std::cout << "Member function callback with value: " << result << std::endl;
    }
};

// A function that takes a std::function callback
void process(int x, std::function<void(int)> callback) {
    std::cout << "Processing value: " << x << std::endl;
    callback(x);  // Invoke the callback function
}

int main() {
    MyClass obj;

    // Using std::bind to bind the member function as a callback
    process(10, std::bind(&MyClass::memberCallback, &obj, std::placeholders::_1));

    // Alternatively, using a lambda to capture the object and call the member function
    process(20, [&obj](int result) {
        obj.memberCallback(result);
    });

    return 0;
}
Back to callbacks