
C 中的回调
回调是作为参数传递给函数或类的 可调用 对象,允许根据特定回调自定义行为
使用回调的原因:
- 编写可以与回调提供的不同逻辑配合使用的通用代码
- 通知调用者某些事件,在运行时提供灵活性
- 在运行期间启用动态行为运行时
C 11 中的可调用对象:
- 函数指针(包括指向成员函数的指针)
- std::function 对象
- Lambda 表达式
- 绑定表达式
- 函数对象(具有重载函数调用operator()的类)
编写函数指针:
1 2 | int (*)(int);
int (* foo_p)(int) = &foo;
|
登录后复制
称呼符号:
1 2 | int foobar(int x, int (*moo)(int));
foobar(a, &foo);
|
登录后复制
std::function 对象:
1 | std:: function <int(int)> stdf_foo = &foo;
|
登录后复制
调用符号:
1 2 | int stdf_foobar(int x, std:: function <int(int)> moo);
stdf_foobar(a, stdf_foo);
|
登录后复制
拉姆达表达式:
1 | stdf_foobar(a, [c](int x) -> int { return 7+c*x; });
|
登录后复制
std::bind 表达式:
1 2 | int nine_x_and_y (int x, int y) { return 9*x + y; }
stdf_foobar(a, std::bind(nine_x_and_y, _1, 3));
|
登录后复制
模板化回调:
1 2 3 | template< class R, class T>
void stdf_transform_every_int_templ(int * v,
unsigned const n, std:: function <R(T)> fp) {...}
|
登录后复制
致电符号:
1 | stdf_transform_every_int_templ<int,int&>(&a[0], 5, &woof);
|
登录后复制
以上是回调如何增强 C 语言的灵活性和定制性?的详细内容。更多信息请关注PHP中文网其他相关文章!