# C++ Function ## callback function * In C++, a callback function is a function that is passed as a parameter to another function and then executed inside that function * allows for customizable operations within the function, as the behavior can be defined by the callback provided by the caller * c++中使用callback的兩種方式function pointer與std::function ### function pointer * A function pointer is a variable that stores the address of a function that can later be called through this pointer ``` #include <iostream> // Function that uses the callback void processValue(int x, void (*cb)(int)) { std::cout << "Processing value: " << x << std::endl; cb(x); // Calling the callback function } // Callback implementation void myCallback(int x) { std::cout << "Callback called with value: " << x << std::endl; } int main() { int a = 5; processValue(a, myCallback); // Passing `myCallback` as a callback function return 0; } ``` * ```typedef``` or ```using``` can improve code readability, maintainability, and ease of use ``` #include <iostream> // Definition of the callback function type typedef void (*CallbackFunction)(int); // Function that uses the callback void processValue(int x, CallbackFunction cb) { std::cout << "Processing value: " << x << std::endl; cb(x); // Calling the callback function } // Callback implementation void myCallback(int x) { std::cout << "Callback called with value: " << x << std::endl; } int main() { int a = 5; processValue(a, myCallback); // Passing `myCallback` as a callback function return 0; } ``` ### std::function * In more complex applications, particularly those involving **class methods as callbacks**, function pointers can be somewhat limiting. To use member functions as callbacks, you typically need to use: * ```std::function``` and ```std::bind``` from the C++ Standard Library (since C++11), which provide a more flexible way to pass callable objects (like **lambda expressions**, **function pointers**, or **bind expressions**). * **Lambda Expressions**: These can capture context and be used as inline callback definitions, enhancing readability and usability. ``` #include <iostream> #include <functional> void processValue(int x, std::function<void(int)> cb) { std::cout << "Processing value: " << x << std::endl; cb(x); // Calling the callback function } int main() { int a = 10; processValue(a, [](int y){ std::cout << "Lambda Callback with value: " << y << std::endl; }); return 0; } ```