回调函数C++11

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/webzhuce/article/details/84947380

什么是回调函数(Callback Function)

回调函数就是一个通过函数指针调用的函数。我们是通过这个函数指针来调用其指向的函数,这就是我们说的回调机制(Callback)。

为什么使用回调机制(Callback)

原因一:使用回调机制可以编写与被调用函数中的逻辑无关的通用代码,并且可以被不同的回调重复使用。
标准算法库的许多功能都使用回调。例如,该for_each算法对迭代器范围内的每项应用一元回调。

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

我们可以用来先递增,然后通过传递适当的calla来打印一个vector,例如:

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使用存储在actions的回调函数,来获得按下某个键时所需的动作。如果玩家选择更改跳跃的按钮,则引擎可以调用下面函数

game_core_instance.update_keybind(newly_selected_key, &player_jump);

然后下次游戏时一旦按下此按钮后,会改变key_pressed对应的回调的行为(调用player_jump)。

回调函数在C++11中的几种类型

  • 函数指针
  • 仿函数
  • Lambda函数
  • std::function 对象/Bind函数

函数指针

函数指针是一种最简单的类型。我们有一个简单的功能foo:

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

一个函数指针类型具有符号

return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to foo has the type:
int (*)(int)

// i.e. f_int_t is a type: function pointer taking one int argument, returning int
typedef int (*f_int_t) (int); 
using f_int_t0 = int(*)(int); //more readable

// 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;
f_int_t0 foo_p = &foo;

使用函数指针类型回调的函数,函数的编写不依赖于回调的工作方式。例如:

void tranform_every_int(int * v, unsigned n, int (*fp)(int))
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]); 
  }
}
int a[5] = {1, 2, 3, 4, 5};
tranform_every_int(&a[0], 5, foo);

指向成员函数的指针

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

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

一个指向某类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)

// 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;

可以使用类T的成员函数指针调用带有类T的成员函数指针的回调函数。

int C_foobar_0 (int x, C& c, int (C::*moo)(int))
{
    return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}

typedef int (C::* f_C_int_t) (int x); 
// analog
int C_foobar_1 (int x, C& c, f_C_int_t moo)
{
    return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}

int C_foobar_2 (int x, C* 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_3 (int x, C* c, int (C::*meow)(int))
{
    if (!c) return x;
    // function pointer meow called for object *c using argument x
    return x + (c->*meow)(x); 
}

 C my_c{2}; // aggregate initialization
 int a = 5;
 int b = C_foobar_0(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback
 std::cout << b;

std::function对象

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;
int stdf_foobar (int x, std::function<int(int)> moo)
{
    return x + moo(x); // std::function moo called
}

std::cout << stdf_foobar(11, stdf_foo) << std::endl;

存储自由函数

int a = 2;
int b = stdf_foobar(a, &foo);
// b == 6 ( 2 + (2+2) )

Lambda表达式

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)

std::bind 表达式

using std::placeholders::_1;
int a = 2;
int b = stdf_foobar(a, std::bind(foo, _1));
// b == 6 == 2 + ( 2 + 2 )

//pointer to member functions
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 )

仿函数

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 )

模板回调类型

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

template<class F>
void transform_every_int_templ(int * v, 
  unsigned const n, F f)
{
  std::cout << "transform_every_int_templ:\n";
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = f(v[i]);
  }
}

int a[5] = { 1, 2, 3, 4, 5 };
transform_every_int_templ(&a[0], 5, std::function<int(int)>{&foo});

参考资料

猜你喜欢

转载自blog.csdn.net/webzhuce/article/details/84947380