在 C ++ 中,何时以及如何使用回调函数?
编辑:
我想看到一个简单的例子来写一个回调函数。
注意:大多数答案涵盖了函数指针,这是在 C ++ 中实现“回调”逻辑的一种可能性,但截至今天,我认为这不是最有利的。
什么是回调(?)以及为什么使用它们(!)
回调是类或函数接受的可调用(请参阅下面的内容),用于根据该回调自定义当前逻辑。
使用回调的一个原因是编写泛型代码,该代码于被调用函数中的逻辑,并且可以与不同的回调重用。
标准算法库<algorithm>
的许多函数都使用回调。例如,for_each
算法将一元回调应用于迭代器范围内的每个项:
template<cl InputIt, cl UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
for (; first != last; ++first) {
f(*first);
}
return f;
}
它可以用来首先递增,然后通过传递适当的可调用来打印向量,例如:
std::vector<double> 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();
cl game_core
{
std::array<void(*)(), total_num_keys> 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) 中的可调用对象?
有关更正式的描述,请参见 cppreference 上的C++ concepts: Callable。
回调功能可以在 C ++ 中以多种方式实现(11),因为有几种不同的东西是可调用 *:
函数指针(包括指向成员函数的指针)
std::function
objects
Lambda 表达式
绑定表达式
函数对象(具有重载函数调用运算符operator()
的类)
*注意:指向数据成员的指针也是可调用的,但根本不调用任何函数。
详细编写回调的几种重要方法
X.1 本文中的“Writing”回调意味着声明和命名回调类型的语法。
X.2“调用”回调是指调用这些对象的语法。
X.3“使用”回调是指使用回调将参数传递给函数时的语法。
注意:从 C++ 17 开始,像f(...)
这样的调用可以写成std::invoke(f, ...)
,它也处理指向成员 case 的指针。
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
声明为我们提供了使事物更具可读性的选项,因为f_int_t
的typedef
也可以写成:
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
}
// og
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
}
// og
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
的成员函数指针来调用采用类T
的成员函数指针的回调函数。
使用一个指向成员函数回调的函数-类似于函数 pointers-非常简单:
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
对象(头<functional>
)
std::function
类是一个多态函数包装器,用于存储、复制或调用可调用对象。
3.1 编写std::function
对象 / 类型表示法
存储可调用的std::function
对象的类型如下所示:
std::function<return_type(parameter_type_1, parameter_type_2, parameter_type_3)>
// i.e. using the above function declaration of foo:
std::function<int(int)> stdf_foo = &foo;
// or C::foo:
std::function<int(const C&, int)> stdf_C_foo = &C::foo;
3.2 回调调用表示法
类std::function
定义了operator()
,可用于调用其目标。
int stdf_foobar (int x, std::function<int(int)> moo)
{
return x + moo(x); // std::function moo called
}
// or
int stdf_C_foobar (int x, C const &c, std::function<int(C const &, int)> 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
expressions
可以传递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<int(int)> 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<cl R, cl T>
void stdf_transform_every_int_templ(int * v,
unsigned const n, std::function<R(T)> fp)
{
for (unsigned i = 0; i < n; ++i)
{
v[i] = fp(v[i]);
}
}
回调类型的更通用(也是最简单的)语法是一个简单的,要推导的模板化参数:
template<cl F>
void transform_every_int_templ(int * v,
unsigned const n, F f)
{
std::cout << "transform_every_int_templ<"
<< type_name<F>() << ">\n";
for (unsigned i = 0; i < n; ++i)
{
v[i] = f(v[i]);
}
}
注意:包含的输出将打印为模板化类型F
推导的类型名称。type_name
的实现在本文的末尾给出。
范围的一元转换的最一般实现是标准库的一部分,即std::transform
,它也是相对于迭代类型的模板。
template<cl InputIt, cl OutputIt, cl UnaryOperation>
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<int,int>(&a[0], 5, &foo);
// a == {3, 4, 5, 6, 7}
stdf_transform_every_int_templ<int, int const &>(&a[0], 5, &muh);
// a == {6, 7, 8, 9, 10}
stdf_transform_every_int_templ<int, int &>(&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<int(int)>{&foo});
print_int(a, 5);
上面的代码打印:
1 2 3 4 5
transform_every_int_templ <int(*)(int)>
3 4 5 6 7
transform_every_int_templ <int(*)(int&)>
6 8 10 12 14
transform_every_int_templ <int& (*)(int&)>
9 11 13 15 17
transform_every_int_templ <main::{lambda(int)#1} >
27 33 39 45 51
transform_every_int_templ <Meow>
108 132 156 180 204
transform_every_int_templ <std::_Bind<int(*(std::_Placeholder<1>, int))(int, int)>>
975 1191 1407 1623 1839
transform_every_int_templ <std::function<int(int)>>
977 1193 1409 1625 1841
上面使用的type_name
实现
#include <type_traits>
#include <typeinfo>
#include <string>
#include <memory>
#include <cxxabi.h>
template <cl T>
std::string type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> 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<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += " &";
else if (std::is_rvalue_reference<T>::value)
r += " &&";
return r;
}
还有做回调的 C 方式:函数指针
// Define a type for the callback signature,
// it is not necessary but makes life easier
// Function pointer called CallbackType that takes a float
// and returns an int
typedef int (*CallbackType)(float);
void DoWork(CallbackType callback)
{
float variable = 0.0f;
// Do calculations
// Call the callback with the variable, and retrieve the
// result
int result = callback(variable);
// Do something with the result
}
int SomeCallback(float variable)
{
int result;
// Interpret variable
return result;
}
int main(int argc, char ** argv)
{
// P in SomeCallback to the DoWork
DoWork(&SomeCallback);
}
现在,如果您想将类方法作为回调传递,则对这些函数指针的声明具有更复杂的声明,例如:
// Declaration:
typedef int (ClName::*CallbackType)(float);
// This method performs work using an object instance
void DoWorkObject(CallbackType callback)
{
// Cl instance to invoke it through
ClName objectInstance;
// Invocation
int result = (objectInstance.*callback)(1.0f);
}
//This method performs work using an object pointer
void DoWorkPointer(CallbackType callback)
{
// Cl pointer to invoke it through
ClName * pointerInstance;
// Invocation
int result = (pointerInstance->*callback)(1.0f);
}
int main(int argc, char ** argv)
{
// P in SomeCallback to the DoWork
DoWorkObject(&ClName::Method);
DoWorkPointer(&ClName::Method);
}
Scott Meyers 举了一个很好的例子:
cl GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);
cl GameCharacter
{
public:
typedef std::function<int (const GameCharacter&)> HealthCalcFunc;
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
: healthFunc(hcf)
{ }
int healthValue() const { return healthFunc(*this); }
private:
HealthCalcFunc healthFunc;
};
我认为这个例子说明了一切。
std::function<>
是编写 C++ 回调的“现代”方式。
Callback function是一个方法,它被传递到一个例程中,并在某个时候被传递给它的例程调用。
这对于制作可重用软件非常有用。例如,许多操作系统 API(如 Windows API)大量使用回调。
例如,如果您想使用文件夹中的文件-您可以使用自己的例程调用 API 函数,并且例程在指定文件夹中的每个文件运行一次。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(47条)