Callbacks in C
A callback is a callable object that is passed as an argument to a function or class, allowing for customization of the behavior based on the specific callback function.
Reasons to use Callbacks:
Callables in C 11:
Writing Function Pointers:
int (*)(int); // Function pointer type taking one int argument, returning int int (* foo_p)(int) = &foo; // Initialize pointer to function foo
Call Notation:
int foobar(int x, int (*moo)(int)); foobar(a, &foo); // Call foobar with pointer to foo as callback
std::function Objects:
std::function<int(int)> stdf_foo = &foo;
Call Notation:
int stdf_foobar(int x, std::function<int(int)> moo); stdf_foobar(a, stdf_foo);
Lambda Expressions:
stdf_foobar(a, [c](int x) -> int { return 7+c*x; });
std::bind Expressions:
int nine_x_and_y (int x, int y) { return 9*x + y; } stdf_foobar(a, std::bind(nine_x_and_y, _1, 3));
Templated Callbacks:
template<class R, class T> void stdf_transform_every_int_templ(int * v, unsigned const n, std::function<R(T)> fp) {...}
Call Notation:
stdf_transform_every_int_templ<int,int&>(&a[0], 5, &woof);
The above is the detailed content of How Do Callbacks Enhance Flexibility and Customization in C ?. For more information, please follow other related articles on the PHP Chinese website!