回调函数C++11_c++11 回调函数-程序员宅基地

技术标签: C++  回调机制  callback  成员函数指针  回调函数  std::function  

什么是回调函数(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});

参考资料

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/webzhuce/article/details/84947380

智能推荐

彻底扒光 通过智能路由器拆解看其本质-程序员宅基地

文章浏览阅读1.7k次。可以看到很多联发科的MT芯片摘自:https://net.zol.com.cn/531/5312999.html彻底扒光 通过智能路由器拆解看其本质2015-07-23 00:40:00[中关村在线 原创] 作者:陈赫|责编:白宁收藏文章 分享到 评论(24)关注智能路由器拆解的朋友们注意啦!我们已经将这五款产品彻底扒开,将主板的真容展现在了大家的眼前。网友们可以看见这些智能路由器主板的做工和用料,我们还为网友们展示了主要的电子元器件,供大家品评观赏。..._路由器拆解

Java--深入JDK和hotspot底层源码剖析Thread的run()、start()方法执行过程_jdk的源码hotspot跟jdk是分开的-程序员宅基地

文章浏览阅读2.1k次,点赞101次,收藏78次。【学习背景】今天主要是来了解Java线程Thread中的run()、start()两个方法的执行有哪些区别,会给出一个简单的测试代码样例,快速理解两者的区别,再从源码层面去追溯start()底层是如何最终调用Thread#run()方法的,个人觉得这样的学习不论对面试,还是实际编程来说都是比较有帮助的。进入正文~学习目录一、代码测试二、源码分析2.1 run()方法2.2 start()方法三、使用总结一、代码测试执行Thread的run()、start()方法的测试代码如下:public_jdk的源码hotspot跟jdk是分开的

透视俄乌网络战之一:数据擦除软件_俄乌网络战观察(一)-程序员宅基地

文章浏览阅读4.4k次,点赞90次,收藏85次。俄乌冲突中,各方势力通过数据擦除恶意软件破坏关键信息基础设施计算机的数据,达到深度致瘫的效果,同时窃取重要敏感信息。_俄乌网络战观察(一)

Maven私服仓库配置-Nexus详解_nexus maven-程序员宅基地

文章浏览阅读1.7w次,点赞23次,收藏139次。Maven 私服是一种特殊的Maven远程仓库,它是架设在局域网内的仓库服务,用来代理位于外部的远程仓库(中央仓库、其他远程公共仓库)。当然也并不是说私服只能建立在局域网,也有很多公司会直接把私服部署到公网,具体还是得看公司业务的性质是否是保密的等等,因为局域网的话只能在公司用,部署到公网的话员工在家里也可以办公使用。_nexus maven

基于AI的计算机视觉识别在Java项目中的使用 (四) —— 准备训练数据_java ocr ai识别训练-程序员宅基地

文章浏览阅读934次。我先用所有的样本数据对模型做几轮初步训练,让深度神经模型基本拟合(数万条记录的训练集,识别率到99%左右),具备初步的识别能力,这时的模型就是“直男”。相较于训练很多轮、拟合程度很高的“油腻男”,它的拟合程度较低,还是“直男愣头青”。..............._java ocr ai识别训练

hibernate 数据库类型 date没有时分秒解决_hibernate解析時間只有年月日沒有時分秒-程序员宅基地

文章浏览阅读688次。一、问题现象:  在数据库表中日期字段中存的日期光有年月日,没有时分秒。二、产生原因:三 解决办法   检查表的相应映射xml文件。 <property name="operateDate" type="Date">如果同上面所写,那问题出在 type类型上了正确写法 :<property name="operateDate" type="java.util..._hibernate解析時間只有年月日沒有時分秒

随便推点

springbbot运行无法编译成功,找不到jar包报错:Error:(3, 46) java: 程序包org.springframework.context.annotation不存在-程序员宅基地

文章浏览阅读1k次,点赞2次,收藏2次。文章目录问题描述:解决方案:问题描述:提示:idea springbbot运行无法编译成功,找不到jar包报错E:\ideaProject\demokkkk\src\main\java\com\example\demo\config\WebSocketConfig.javaError:(3, 46) java: 程序包org.springframework.context.annotation不存在Error:(4, 46) java: 程序包org.springframework.conte_error:(3, 46) java: 程序包org.springframework.context.annotation不存在

react常见面试题_recate面试-程序员宅基地

文章浏览阅读6.4k次,点赞6次,收藏36次。1、redux中间件中间件提供第三方插件的模式,自定义拦截 action -&gt; reducer 的过程。变为 action -&gt; middlewares -&gt; reducer 。这种机制可以让我们改变数据流,实现如异步 action ,action 过滤,日志输出,异常报告等功能。常见的中间件:redux-logger:提供日志输出redux-thunk:处理异步操作..._recate面试

交叉编译jpeglib遇到的问题-程序员宅基地

文章浏览阅读405次。由于要在开发板中加载libjpeg,不能使用gcc编译的库文件给以使用,需要自己配置使用另外的编译器编译该库文件。/usr/bin/ld:.libs/jaricom.o:RelocationsingenericELF(EM:40)/usr/bin/ld:.libs/jaricom.o:RelocationsingenericELF(EM:40)...._jpeg_utils.lo: relocations in generic elf (em: 8) error adding symbols: file

【办公类-22-06】周计划系列(1)“信息窗” (2024年调整版本)-程序员宅基地

文章浏览阅读578次,点赞10次,收藏17次。【办公类-22-06】周计划系列(1)“信息窗” (2024年调整版本)

SEO优化_百度seo resetful-程序员宅基地

文章浏览阅读309次。SEO全称为Search Engine Optimization,中文解释为搜索引擎优化。一般指通过对网站内部调整优化及站外优化,使网站满足搜索引擎收录排名需求,在搜索引擎中提高关键词排名,从而把精准..._百度seo resetful

回归预测 | Matlab实现HPO-ELM猎食者算法优化极限学习机的数据回归预测_猎食者优化算法-程序员宅基地

文章浏览阅读438次。回归预测 | Matlab实现HPO-ELM猎食者算法优化极限学习机的数据回归预测_猎食者优化算法

推荐文章

热门文章

相关标签