什么是回调?以及为什么要使用它们!

什么是回调?以及为什么要使用它们!

回调是一个类或函数接受的可调用(见下文),用于根据该回调自定义当前逻辑。

使用回调的原因之一是编写通用代码,该代码独立于被调用函数中的逻辑,并且可以与不同的回调一起使用。

标准算法库的许多函数都使用回调。例如,该for_each算法对一系列迭代器中的每个项目应用一元回调:

template

UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)

{

for (; first != last; ++first) {

f(*first);

}

return f;

}

它可用于首先递增,然后通过传递适当的可调用对象来打印向量,例如:

std::vector v{ 1.0, 2.2, 4.0, 5.5, 7.2 };

double r = 4.0;

std::for_each(v.begin(), v.end(), [&](double & v) { v += r; });

std::for_each(v.begin(), v.end(), [](double v) { std::cout << v << " "; });

结果打印

5 6.2 8 9.5 11.2

回调的另一个应用是通知某些事件的调用者,这实现了一定程度的静态/编译时间灵活性。

就我个人而言,我使用了一个使用两种不同回调的本地优化库:

如果需要函数值和基于输入值向量的梯度(逻辑回调:函数值确定/梯度推导),则调用第一个回调。第二个回调为每个算法步骤调用一次,并接收有关算法收敛的某些信息(通知回调)。

因此,库设计者不负责决定通过通知回调提供给程序员的信息会发生什么,他不必担心如何实际确定函数值,因为它们是由逻辑回调提供的。把这些事情做好是图书馆用户的一项任务,让图书馆保持苗条和更通用。

此外,回调可以启用动态运行时行为。

想象一下某种游戏引擎类,它有一个函数被触发,每次用户按下键盘上的一个按钮和一组控制你的游戏行为的函数。通过回调,您可以(重新)决定在运行时将采取哪些操作。

void player_jump();

void player_crouch();

class game_core

{

std::array actions;

//

void key_pressed(unsigned key_id)

{

if(actions[key_id]) actions[key_id]();

}

// update keybind from menu

void update_keybind(unsigned key_id, void(*new_action)())

{

actions[key_id] = new_action;

}

};

当按下某个键时,该函数key_pressed使用存储在其中的回调actions来获取所需的行为。如果玩家选择改变跳跃按钮,引擎可以调用

game_core_instance.update_keybind(newly_selected_key, &player_jump);

从而在下次游戏中按下此按钮后更改调用key_pressed(调用player_jump)的行为。

C++(11)中的可调用对象是什么?

有关更正式的描述,请参阅C++ 概念:可在 cppreference 上调用。

回调功能可以在 C++(11) 中以多种方式实现,因为有几种不同的东西是可调用的*:

函数指针(包括指向成员函数的指针)std::function 对象Lambda 表达式绑定表达式函数对象(具有重载函数调用运算符的类operator())

*注意:指向数据成员的指针也是可调用的,但根本不调用任何函数。

详细编写回调的几种重要方式

X.1 在这篇文章中“编写”一个回调是指声明和命名回调类型的语法。X.2 “调用”回调是指调用这些对象的语法。X.3 “使用”回调是指使用回调将参数传递给函数时的语法。

注意:从 C++17 开始,f(...)可以将类似的调用编写为std::invoke(f, ...)也处理指向成员大小写的指针。

1. 函数指针

函数指针是回调可以具有的“最简单”(就通用性而言;就可读性而言可能是最差的)类型。

让我们有一个简单的功能foo:

int foo (int x) { return 2+x; }

1.1 编写函数指针/类型符号

甲函数指针类型具有符号

return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. a pointer to foo has the type:

int (*)(int)

其中一个名为函数指针类型的样子

return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. f_int_t is a type: function pointer taking one int argument, returning int

typedef int (*f_int_t) (int);

// foo_p is a pointer to function taking int returning int

// initialized by pointer to function foo taking int returning int

int (* foo_p)(int) = &foo;

// can alternatively be written as

f_int_t foo_p = &foo;

该using声明给我们的选项,以使事情更易读一点点,因为typedef对f_int_t也可以写为:

using f_int_t = int(*)(int);

其中(至少对我而言)更清楚的f_int_t是新类型别名和函数指针类型的识别也更容易

使用函数指针类型的回调函数声明将是:

// foobar having a callback argument named moo of type

// pointer to function returning int taking int as its argument

int foobar (int x, int (*moo)(int));

// if f_int is the function pointer typedef from above we can also write foobar as:

int foobar (int x, f_int_t moo);

1.2 回调调用符号

调用符号遵循简单的函数调用语法:

int foobar (int x, int (*moo)(int))

{

return x + moo(x); // function pointer moo called using argument x

}

// analog

int foobar (int x, f_int_t moo)

{

return x + moo(x); // function pointer moo called using argument x

}

1.3 回调使用符号和兼容类型

可以使用函数指针调用带有函数指针的回调函数。

使用接受函数指针回调的函数相当简单:

int a = 5;

int b = foobar(a, foo); // call foobar with pointer to foo as callback

// can also be

int b = foobar(a, &foo); // call foobar with pointer to foo as callback

1.4 示例

可以编写一个不依赖于回调如何工作的函数:

void tranform_every_int(int * v, unsigned n, int (*fp)(int))

{

for (unsigned i = 0; i < n; ++i)

{

v[i] = fp(v[i]);

}

}

回调可能在:

int double_int(int x) { return 2*x; }

int square_int(int x) { return x*x; }

用法:

int a[5] = {1, 2, 3, 4, 5};

tranform_every_int(&a[0], 5, double_int);

// now a == {2, 4, 6, 8, 10};

tranform_every_int(&a[0], 5, square_int);

// now a == {4, 16, 36, 64, 100};

2. 成员函数指针

指向成员函数(某个类C)的指针是一种特殊类型(甚至更复杂)的函数指针,它需要一个类型的对象C来操作。

struct C

{

int y;

int foo(int x) const { return x+y; }

};

2.1 编写指向成员函数/类型符号的指针

甲成员函数指针类型对于某些类T具有符号

// can have more or less parameters

return_type (T::*)(parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. a pointer to C::foo has the type

int (C::*) (int)

其中指向成员函数的命名指针将 - 类似于函数指针 - 看起来像这样:

return_type (T::* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. a type `f_C_int` representing a pointer to member function of `C`

// taking int returning int is:

typedef int (C::* f_C_int_t) (int x);

// The type of C_foo_p is a pointer to member function of C taking int returning int

// Its value is initialized by a pointer to foo of C

int (C::* C_foo_p)(int) = &C::foo;

// which can also be written using the typedef:

f_C_int_t C_foo_p = &C::foo;

示例:声明一个函数,将指向成员函数回调的指针作为其参数之一:

// C_foobar having an argument named moo of type pointer to member function of C

// where the callback returns int taking int as its argument

// also needs an object of type c

int C_foobar (int x, C const &c, int (C::*moo)(int));

// can equivalently declared using the typedef above:

int C_foobar (int x, C const &c, f_C_int_t moo);

2.2 回调调用符号

C对于类型的对象,可以调用指向成员函数的指针,方法是C对解除引用的指针使用成员访问操作。 注意:需要括号!

int C_foobar (int x, C const &c, int (C::*moo)(int))

{

return x + (c.*moo)(x); // function pointer moo called for object c using argument x

}

// analog

int C_foobar (int x, C const &c, f_C_int_t moo)

{

return x + (c.*moo)(x); // function pointer moo called for object c using argument x

}

注意:如果指向的指针C可用,则语法是等效的(指向的指针也C必须取消引用):

int C_foobar_2 (int x, C const * c, int (C::*meow)(int))

{

if (!c) return x;

// function pointer meow called for object *c using argument x

return x + ((*c).*meow)(x);

}

// or equivalent:

int C_foobar_2 (int x, C const * c, int (C::*meow)(int))

{

if (!c) return x;

// function pointer meow called for object *c using argument x

return x + (c->*meow)(x);

}

2.3 回调使用符号和兼容类型

T可以使用class的成员函数指针调用采用class 的成员函数指针的回调函数T。

使用带有指向成员函数回调指针的函数 - 类似于函数指针 - 也非常简单:

C my_c{2}; // aggregate initialization

int a = 5;

int b = C_foobar(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback

3.std::function对象(头文件

该std::function班是一个多态函数包装到存储,复制或调用可调用。

3.1 编写std::function对象/类型符号

std::function存储可调用对象的类型如下所示:

std::function

// i.e. using the above function declaration of foo:

std::function stdf_foo = &foo;

// or C::foo:

std::function stdf_C_foo = &C::foo;

3.2 回调调用符号

该类std::function已operator()定义可用于调用其目标。

int stdf_foobar (int x, std::function moo)

{

return x + moo(x); // std::function moo called

}

// or

int stdf_C_foobar (int x, C const &c, std::function moo)

{

return x + moo(c, x); // std::function moo called using c and x

}

3.3 回调使用符号和兼容类型

该std::function回调比函数指针或指针成员函数更为通用的,因为不同类型的可以被传递并隐式转换成std::function对象。

3.3.1 函数指针和成员函数指针

一个函数指针

int a = 2;

int b = stdf_foobar(a, &foo);

// b == 6 ( 2 + (2+2) )

或指向成员函数的指针

int a = 2;

C my_c{7}; // aggregate initialization

int b = stdf_C_foobar(a, c, &C::foo);

// b == 11 == ( 2 + (7+2) )

可以使用。

3.3.2 Lambda 表达式

来自 lambda 表达式的未命名闭包可以存储在std::function对象中:

int a = 2;

int c = 3;

int b = stdf_foobar(a, [c](int x) -> int { return 7+c*x; });

// b == 15 == a + (7*c*a) == 2 + (7+3*2)

3.3.3std::bind表达式

std::bind可以传递表达式的结果。例如通过将参数绑定到函数指针调用:

int foo_2 (int x, int y) { return 9*x + y; }

using std::placeholders::_1;

int a = 2;

int b = stdf_foobar(a, std::bind(foo_2, _1, 3));

// b == 23 == 2 + ( 9*2 + 3 )

int c = stdf_foobar(a, std::bind(foo_2, 5, _1));

// c == 49 == 2 + ( 9*5 + 2 )

也可以将对象绑定为调用成员函数指针的对象:

int a = 2;

C const my_c{7}; // aggregate initialization

int b = stdf_foobar(a, std::bind(&C::foo, my_c, _1));

// b == 1 == 2 + ( 2 + 7 )

3.3.4 函数对象

具有适当operator()重载的类的对象也可以存储在std::function对象中。

struct Meow

{

int y = 0;

Meow(int y_) : y(y_) {}

int operator()(int x) { return y * x; }

};

int a = 11;

int b = stdf_foobar(a, Meow{8});

// b == 99 == 11 + ( 8 * 11 )

3.4 示例

更改要使用的函数指针示例 std::function

void stdf_tranform_every_int(int * v, unsigned n, std::function fp)

{

for (unsigned i = 0; i < n; ++i)

{

v[i] = fp(v[i]);

}

}

为该函数提供了更多的实用性,因为(参见 3.3)我们有更多的可能性来使用它:

// using function pointer still possible

int a[5] = {1, 2, 3, 4, 5};

stdf_tranform_every_int(&a[0], 5, double_int);

// now a == {2, 4, 6, 8, 10};

// use it without having to write another function by using a lambda

stdf_tranform_every_int(&a[0], 5, [](int x) -> int { return x/2; });

// now a == {1, 2, 3, 4, 5}; again

// use std::bind :

int nine_x_and_y (int x, int y) { return 9*x + y; }

using std::placeholders::_1;

// calls nine_x_and_y for every int in a with y being 4 every time

stdf_tranform_every_int(&a[0], 5, std::bind(nine_x_and_y, _1, 4));

// now a == {13, 22, 31, 40, 49};

4. 模板化回调类型

使用模板,调用回调的代码甚至可以比使用std::function对象更通用。

请注意,模板是编译时功能,是编译时多态性的设计工具。如果要通过回调实现运行时动态行为,模板会有所帮助,但它们不会引起运行时动态。

4.1 编写(类型符号)和调用模板化回调

std_ftransform_every_int通过使用模板可以进一步推广即上面的代码:

template

void stdf_transform_every_int_templ(int * v,

unsigned const n, std::function fp)

{

for (unsigned i = 0; i < n; ++i)

{

v[i] = fp(v[i]);

}

}

回调类型的语法更通用(也是最简单的),它是一个简单的、待推导的模板化参数:

template

void transform_every_int_templ(int * v,

unsigned const n, F f)

{

std::cout << "transform_every_int_templ<"

<< type_name() << ">\n";

for (unsigned i = 0; i < n; ++i)

{

v[i] = f(v[i]);

}

}

注意:包含的输出打印为模板化类型推导出的类型名称F。type_name本文末尾给出了 的实现。

范围的一元转换的最通用实现是标准库的一部分,即std::transform,它也针对迭代类型进行了模板化。

template

OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,

UnaryOperation unary_op)

{

while (first1 != last1) {

*d_first++ = unary_op(*first1++);

}

return d_first;

}

4.2 使用模板化回调和兼容类型的示例

模板化std::function回调方法的兼容类型stdf_transform_every_int_templ与上述类型相同(参见 3.4)。

然而,使用模板化版本,所使用的回调的签名可能会发生一些变化:

// Let

int foo (int x) { return 2+x; }

int muh (int const &x) { return 3+x; }

int & woof (int &x) { x *= 4; return x; }

int a[5] = {1, 2, 3, 4, 5};

stdf_transform_every_int_templ(&a[0], 5, &foo);

// a == {3, 4, 5, 6, 7}

stdf_transform_every_int_templ(&a[0], 5, &muh);

// a == {6, 7, 8, 9, 10}

stdf_transform_every_int_templ(&a[0], 5, &woof);

注意:(std_ftransform_every_int非模板化版本;见上文)确实使用foo但不使用muh.

// Let

void print_int(int * p, unsigned const n)

{

bool f{ true };

for (unsigned i = 0; i < n; ++i)

{

std::cout << (f ? "" : " ") << p[i];

f = false;

}

std::cout << "\n";

}

的普通模板参数transform_every_int_templ可以是所有可能的可调用类型。

int a[5] = { 1, 2, 3, 4, 5 };

print_int(a, 5);

transform_every_int_templ(&a[0], 5, foo);

print_int(a, 5);

transform_every_int_templ(&a[0], 5, muh);

print_int(a, 5);

transform_every_int_templ(&a[0], 5, woof);

print_int(a, 5);

transform_every_int_templ(&a[0], 5, [](int x) -> int { return x + x + x; });

print_int(a, 5);

transform_every_int_templ(&a[0], 5, Meow{ 4 });

print_int(a, 5);

using std::placeholders::_1;

transform_every_int_templ(&a[0], 5, std::bind(foo_2, _1, 3));

print_int(a, 5);

transform_every_int_templ(&a[0], 5, std::function{&foo});

print_int(a, 5);

上面的代码打印:

1 2 3 4 5

transform_every_int_templ

3 4 5 6 7

transform_every_int_templ

6 8 10 12 14

transform_every_int_templ

9 11 13 15 17

transform_every_int_templ

27 33 39 45 51

transform_every_int_templ

108 132 156 180 204

transform_every_int_templ , int))(int, int)>>

975 1191 1407 1623 1839

transform_every_int_templ >

977 1193 1409 1625 1841

type_name 上面使用的实现

#include

#include

#include

#include

#include

template

std::string type_name()

{

typedef typename std::remove_reference::type TR;

std::unique_ptr own

(abi::__cxa_demangle(typeid(TR).name(), nullptr,

nullptr, nullptr), std::free);

std::string r = own != nullptr?own.get():typeid(TR).name();

if (std::is_const::value)

r += " const";

if (std::is_volatile::value)

r += " volatile";

if (std::is_lvalue_reference::value)

r += " &";

else if (std::is_rvalue_reference::value)

r += " &&";

return r;

}

相关推荐

365bet手机在线 广州精子库捐献精子流程图分享,四种报名方式可任选
365bet手机在线 关于卡顿问题的临时解决方案

关于卡顿问题的临时解决方案

📅 07-30 👁️ 5607
365bet手机在线 《剑网3》如何放回稻香村的详细方法