Callbacks in C
Callbacks are callable objects accepted by a function or class, used to customize the current logic based on the callback.
When to use Callbacks:
Callables in C 11:
Callbacks can take various forms, all considered "callable":
Callback Notation:
1. Function Pointers
2. Pointer to Member Function
3. std::function Objects
4. Templated Callbacks
This allows for more generic code.
Compatible Callback Types:
Examples:
Function Pointer Example:
void tranform_every_int(int * v, unsigned n, int (*fp)(int)); int double_int(int x) { return 2*x; } int square_int(int x) { return x*x; }
std::function Object Example:
void stdf_tranform_every_int(int * v, unsigned n, std::function<int(int)> fp); int a[5] = {1, 2, 3, 4, 5}; stdf_tranform_every_int(&a[0], 5, Meow{8});
Templated Callback Example:
int nine_x_and_y (int x, int y) { return 9*x + y; } using std::placeholders::_1; stdf_transform_every_int_templ(&a[0], 5, std::bind(nine_x_and_y, _1, 4));
The above is the detailed content of How Can Callbacks Enhance C Code Functionality?. For more information, please follow other related articles on the PHP Chinese website!