其他分享
首页 > 其他分享> > C中的回调函数

C中的回调函数

作者:互联网

在C中,何时以及如何使用回调函数?

编辑:
我想看一个编写回调函数的简单示例.

解决方法:

注意:大多数答案都涵盖了函数指针,这是在C中实现“回调”逻辑的一种可能性,但是到目前为止并不是我认为最有利的一种.

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

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

使用回调的一个原因是编写通用代码,该代码与被调用函数中的逻辑无关,并且可以与不同的回调一起使用.

标准算法库的许多功能<算法>使用回调.例如,for_each算法对一系列迭代器中的每个项应用一元回调:

template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
  for (; first != last; ++first) {
    f(*first);
  }
  return f;
}

可以通过传递适当的callables来首先递增然后打印矢量,例如:

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();

class 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使用存储在动作中的回调来获得按下某个键时所需的行为.
如果玩家选择更改跳跃按钮,则引擎可以呼叫

game_core_instance.update_keybind(newly_selected_key, &player_jump);

因此,下次游戏时按下此按钮后,会更改对key_pressed(调用player_jump)的调用行为.

什么是C(11)中的可赎回物?

有关更正式的说明,请参阅cppreference上的C++ concepts: Callable.

回调功能可以通过C(11)中的几种方式实现,因为几个不同的东西可以调用*:

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

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

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

> X.1在此帖子中“编写”回调意味着声明和命名回调类型的语法.
> X.2“调用”回调是指调用这些对象的语法.
> X.3“使用”回调是指使用回调将参数传递给函数时的语法.

注意:从C17开始,像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声明为我们提供了使事情更具可读性的选项,因为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
}
// 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的成员函数指针调用带有类T的成员函数指针的回调函数.

使用一个指向成员函数回调的函数是-in类似于函数指针 – 也很简单:

 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对象(header< functional>)

std :: function类是一个多态函数包装器,用于存储,复制或调用callables.

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.3 std :: 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<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<class R, class 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<class 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<class InputIt, class OutputIt, class 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 <class 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,callback,function-pointers
来源: https://codeday.me/bug/20190916/1806549.html