当前位置: 首页 > 编程日记 > 正文

c++回调函数 callback

1Callback方式
Callback
的本质是设置一个函数指针进去,然后在需要需要触发某个事件时调用该方法, 比如Windows的窗口消息处理函数就是这种类型。比如下面的示例代码,我们在Download完成时需要触发一个通知外面的事件:

 1 typedef void (__stdcall *DownloadCallback)(const char* pURL, bool bOK);  
 2 void DownloadFile(const char* pURL, DownloadCallback callback)  
 3 {  
 4     cout << "downloading: " << pURL << "" << endl;  
 5     callback(pURL, true);  
 6 }  
 7 void __stdcall OnDownloadFinished(const char* pURL, bool bOK)  
 8 {  
 9     cout << "OnDownloadFinished, URL:" << pURL << "    status:" << bOK << endl;  
10 } 

(2)Sink方式

Sink的本质是你按照对方要求实现一个C++接口,然后把你实现的接口设置给对方,对方需要触发事件时调用该接口, COM中连接点就是居于这种方式。上面下载文件的需求,如果用Sink实现,代码如下:

 1 class IDownloadSink  
 2 {  
 3 public:  
 4     virtual void OnDownloadFinished(const char* pURL, bool bOK) = 0;  
 5 };  
 6     
 7     
 8 class CMyDownloader  
 9 {  
10 public:  
11     CMyDownloader(IDownloadSink* pSink)  
12         :m_pSink(pSink)  
13     {  
14     }  
15     
16     void DownloadFile(const char* pURL)  
17     {  
18         cout << "downloading: " << pURL << "" << endl;  
19         if(m_pSink != NULL)  
20         {  
21             m_pSink->OnDownloadFinished(pURL, true);  
22         }  
23     }  
24     
25 private:  
26     IDownloadSink* m_pSink;  
27 };  
28     
29 class CMyFile: public IDownloadSink  
30 {  
31 public:  
32     void download()  
33     {  
34         CMyDownloader downloader(this);  
35         downloader.DownloadFile("www.baidu.com");  
36     }  
37     
38     virtual void OnDownloadFinished(const char* pURL, bool bOK)  
39     {  
40         cout << "OnDownloadFinished, URL:" << pURL << "    status:" << bOK << endl;  
41     }  
42 };  

(3)Delegate方式
    Delegate
的本质是设置成员函数指针给对方,然后让对方在需要触发事件时调用。C#中用Delegate的方式实现Event,让C++程序员很是羡慕,C++中因为语言本身的关系,要实现Delegate还是很麻烦的。上面的例子我们用Delegate的方式实现如下:

class CDownloadDelegateBase  
{  
public:  virtual void Fire(const char* pURL, bool bOK) = 0;  
};  template<typename O, typename T>  
class CDownloadDelegate: public CDownloadDelegateBase  
{  typedef void (T::*Fun)(const char*, bool);  
public:  CDownloadDelegate(O* pObj = NULL, Fun pFun = NULL)  :m_pFun(pFun), m_pObj(pObj)  {  }  virtual void Fire(const char* pURL, bool bOK)  {  if(m_pFun != NULL  && m_pObj != NULL)  {  (m_pObj->*m_pFun)(pURL, bOK);  }  }  private:  Fun m_pFun;  O* m_pObj;  
};  template<typename O, typename T>  
CDownloadDelegate<O,T>* MakeDelegate(O* pObject, void (T::*pFun)(const char* pURL, bool))  
{  return new CDownloadDelegate<O, T>(pObject, pFun);  
}  class CDownloadEvent  
{  
public:  ~CDownloadEvent()  {  vector<CDownloadDelegateBase*>::iterator itr = m_arDelegates.begin();  while (itr != m_arDelegates.end())  {  delete *itr;  ++itr;  }  m_arDelegates.clear();  }  void operator += (CDownloadDelegateBase* p)  {  m_arDelegates.push_back(p);  }  void operator -= (CDownloadDelegateBase* p)  {  ITR itr = remove(m_arDelegates.begin(), m_arDelegates.end(), p);  ITR itrTemp = itr;  while (itrTemp != m_arDelegates.end())  {  delete *itr;  ++itr;  }  m_arDelegates.erase(itr, m_arDelegates.end());  }  void operator()(const char* pURL, bool bOK)  {  ITR itrTemp = m_arDelegates.begin();  while (itrTemp != m_arDelegates.end())  {  (*itrTemp)->Fire(pURL, bOK);  ++itrTemp;  }  }  private:  vector<CDownloadDelegateBase*> m_arDelegates;  typedef vector<CDownloadDelegateBase*>::iterator ITR;  
};  class CMyDownloaderEx  
{  
public:  void DownloadFile(const char* pURL)  {  cout << "downloading: " << pURL << "" << endl;  downloadEvent(pURL, true);  }  CDownloadEvent downloadEvent;  
};  class CMyFileEx  
{  
public:  void download()  {  CMyDownloaderEx downloader;  downloader.downloadEvent += MakeDelegate(this, &CMyFileEx::OnDownloadFinished);  downloader.DownloadFile("www.baidu.com");  }  virtual void OnDownloadFinished(const char* pURL, bool bOK)  {  cout << "OnDownloadFinished, URL:" << pURL << "    status:" << bOK << endl;  }  
}; 

    可以看到Delegate的方式代码量比上面其他2种方式大多了,并且我们上面是固定参数数量和类型的实现方式,如果要实现可变参数,要更加麻烦的多。可变参数的方式可以参考这2种实现:

Yet Another C#-style Delegate Class in Standard C++
Member Function Pointers and the Fastest Possible C++ Delegates

我们可以用下面的代码测试我们上面的实现:

int _tmain(int argc, _TCHAR* argv[])  
{  DownloadFile("www.baidu.com", OnDownloadFinished);  CMyFile f1;  f1.download();  CMyFileEx ff;  ff.download();  system("pause");  return 0;  
}  

最后简单比较下上面3种实现回调的方法:


第一种Callback的方法是面向过程的,使用简单而且灵活,正如C语言本身。
第二种Sink的方法是面向对象的,在C++里使用较多,可以在一个Sink里封装一组回调接口,适用于一系列比较固定的回调事件。
第三种Delegate的方法也是面向对象的,和Sink封装一组接口不同,Delegate的封装是以函数为单位,粒度比Sink更小更灵活。

你更倾向于用哪种方式来实现回调?

还有一种是通过sigslot信号槽机制来实现委托

相关sigslot的用法可以参考这篇文章。

相关头文件下载地址

转载于:https://www.cnblogs.com/poissonnotes/p/4396082.html

相关文章:

【微信小程序之画布】终:手指触摸画板实现

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 先看效果图&#xff1a; wxml <!--pages/shouxieban/shouxieban.wxml--> <view class"container"><view>手写板&#xff08;请在下方区域手写内容&…

Android开发中应避免的重大错误

by Varun Barad由Varun Barad Android开发中应避免的重大错误 (Critical mistakes to avoid in Android development) As many pioneers and leaders in different fields have paraphrased:正如许多不同领域的开拓者和领导人所说&#xff1a; In any endeavor, it is import…

机房收费系统(VB.NET)——超具体的报表制作过程

之前做机房收费系统用的报表是GridReport&#xff0c;这次VB.NET重构中用到了VisualStudio自带的报表控件。刚開始当然对这块功能非常不熟悉&#xff0c;只是探究了一段时间后还是把它做出来了。 以下把在VisualStudio&#xff08;我用的是VisualStudio2013&#xff0c;假设与您…

微信小程序实现画布自适应各种手机尺寸

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 解决的问题&#xff1a; 画布&#xff0c;动画等js里面的操作&#xff0c;默认是px而不是rpx, 无法根据手机屏幕自适应 达到的效果&#xff1a; 让画布&#xff0c;动画在不同分辨…

网易新闻首页实现

http://www.2cto.com/kf/201409/330299.html IOS后台运行机制详解&#xff08;二&#xff09; http://blog.csdn.net/enuola/article/details/9148691转载于:https://www.cnblogs.com/itlover2013/p/4403061.html

阿联酋gitex_航空公司网站不在乎您的隐私后续行动:阿联酋航空以以下方式回应我的文章:...

阿联酋gitexby Konark Modi通过Konark Modi 航空公司网站不在乎您的隐私后续行动&#xff1a;阿联酋航空对我的文章进行了全面否认 (Airline websites don’t care about your privacy follow-up: Emirates responds to my article with full-on denial) Yesterday, The Regis…

微信小程序把缓存的数组动态渲染到页面

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 代码实现的目的&#xff1a;当页面销毁的时候&#xff0c;页面的参数状态还是能够保存。 show_img函数实现&#xff1a; 创建一个数组保存到缓存&#xff0c;遍历缓存的list_stutas对…

Find Minimumd in Rotated Sorted Array

二分搜索查最小数&#xff0c;from mid to分别为区间的第一个&#xff0c;中位数&#xff0c;和最后一个数 if(from<mid&&mid<to)//顺序&#xff0c;第一个即为最小值 return from; if(from>mid)//发现逆序&#xff0c;则最小值在这个区间&#xff0c;2分搜索…

在DataTable中更新、删除数据

在DataTable中选择记录 /*在DataTable中选择记录*//* 向DataTable中插入记录如上&#xff0c;更新和删除如下:* ----但是在更新和删除前&#xff0c;首先要找出要更新和删除的记录。* 一种方法是遍历DataRow&#xff0c;搜索想要的记录&#xff0c;* --〉然而更聪明的办法是使用…

使用TensorFlow进行机器学习即服务

by Kirill Dubovikov通过基里尔杜博维科夫(Kirill Dubovikov) 使用TensorFlow进行机器学习即服务 (Machine Learning as a Service with TensorFlow) Imagine this: you’ve gotten aboard the AI Hype Train and decided to develop an app which will analyze the effective…

浏览器加载、解析、渲染的过程

最近在学习性能优化&#xff0c;学习了雅虎军规 &#xff0c;可是觉着有点云里雾里的&#xff0c;因为里面有些东西虽然自己也一直在使用&#xff0c;但是感觉不太明白所以然&#xff0c;比如减少DNS查询&#xff0c;css和js文件的顺序。所以就花了时间去了解浏览器的工作&…

《转》java设计模式--工厂方法模式(Factory Method)

本文转自&#xff1a;http://www.cnblogs.com/archimedes/p/java-factory-method-pattern.html 工厂方法模式&#xff08;别名&#xff1a;虚拟构造&#xff09; 定义一个用于创建对象的接口&#xff0c;让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到其子类…

微信小程序去除左上角返回的按钮

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 解决方法有两种&#xff1b; 1.把该页面设置为tab页面或者主页 ; 2.进入该页面使用 wx.reLaunch(); 示例 wx.reLaunch({url: ../detail/detail,}) 这样有一个弊端&#xff0c;就是…

我的第一个web_登陆我的第一个全栈Web开发人员职位

我的第一个webby Robert Cooper罗伯特库珀(Robert Cooper) 登陆我的第一个全栈Web开发人员职位 (Landing My First Full Stack Web Developer Job) This is the story of the steps I took to get my first job as a full stack web developer. I think it’s valuable to sha…

HTTP请求报文和HTTP响应报文(转)

原文地址&#xff1a;http://blog.csdn.net/zhangliang_571/article/details/23508953 HTTP报文是面向文本的&#xff0c;报文中的每一个字段都是一些ASCII码串&#xff0c;各个字段的长度是不确定的。HTTP有两类报文&#xff1a;请求报文和响应报文。 HTTP请求报文 一个HTTP请…

微信小程序用户未授权bug解决方法,微信小程序获取用户信息失败解决方法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; bug示例图&#xff1a; 导致这个bug的原因是 wx.getUserInfo(OBJECT) 接口做了调整&#xff1b; 请看官方文档的描述&#xff1a; wx.getUserInfo(OBJECT) 注意&#xff1a;此接口有…

格式化json日期'/Date(-62135596800000)/'

日期经过json序列化之后&#xff0c;变成了/Date(-62135596800000)/字符串&#xff0c;在显示数据时&#xff0c;我们需要解释成正常的日期。 Insus.NET和js库中&#xff0c;写了一个jQuery扩展方法&#xff1a; $.extend({JsonDateParse: function (value) {if (value /Date(…

aws lambda使用_使用AWS Lambda安排Slack消息

aws lambda使用Migrating to serverless brings a lot of questions. How do you do some of the non-serverless tasks, such as a cronjob in a serverless application?迁移到无服务器带来了很多问题。 您如何执行一些非无服务器的任务&#xff0c;例如无服务器应用程序中的…

微信小程序模块化开发 include与模板开发 template

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 1. include 是引用整个wxml文件&#xff0c;我通常会配合js&#xff0c;css一起使用&#xff1b; 使用场景&#xff0c;需要封装事件和微信 api 的公共模块。 2.template &#xff…

winform解析json

在使用C#开发爬虫程序时&#xff0c;会遇到需要解析json字符串的情况。对于json字符串可以使用正则表达式的形式进行解析&#xff0c;更为方便的方法是使用Newtonsoft.Json来实现。 Nuget添加应用包 在工程上右键——【管理Nuget程序包】浏览找到要安装的程序包Newtonsoft.Jso…

Oracle11g密码忘记处理方法

c:\>sqlplus /nolog sql>connect / as sysdba sql>alter user 用户名 identified by 密码;&#xff08;注意在这里输入的密码是区分大小写的&#xff09; 改完之后你可以输入 sql>connect 用户名/密码 as sysdba进行验证 转载于:https://www.cnblogs.com/imhuanxi…

hic染色体构想_了解微服务:从构想到起点

hic染色体构想by Michael Douglass迈克尔道格拉斯(Michael Douglass) 了解微服务&#xff1a;从构想到起点 (Understanding Microservices: From Idea To Starting Line) Over the last two months, I have invested most of my free time learning the complete ins-and-outs…

[python]关于字符串查找和re正则表达式的效率对比

最近需要在python中做大日志文件中做正则匹配 开始直接在for in 中每行做re.findall&#xff0c;后来发现&#xff0c;性能不行&#xff0c;就在re前面做一个基本的字符串包含判断 (str in str)&#xff0c;如果不包含直接continue 效率对比&#xff1a; 1、只做一次包含判断&a…

微信小程序客服功能 把当前页面的信息卡片发送给客服

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 需求&#xff1a;微信小程序客服带详情页 &#xff0c; 场景&#xff1a;一个人通过微信小程序接入微信客服&#xff0c;聊天后带上入口链接 效果图&#xff1a; 写法&#xff1a; …

phpcms标签大全V9

转自&#xff1a;http://blog.csdn.net/cloudday/article/details/7343448调用头部 尾部{template "content","header"} 、 {template "content","footer"}{siteurl($siteid)} 首页链接地址 <a href"{siteurl($siteid)}/&q…

多伦多到温莎_我想要freeCodeCamp Toronto的Twitter来发布报价,所以我做了一个免费的bot来做到这一点。...

多伦多到温莎If you read About time, you’ll know that I’m a big believer in spending time now on building things that save time in the future. To this end, I built a simple Twitter bot in Go that would occasionally post links to my articles and keep my ac…

Linux常用命令汇总(持续更新中)

命令说明注意点cat access.log | wc -l统计行数awk命令可以做到同样的想过&#xff1a;cat access.log | awk END {print NR}grep vnc /var/log/messages查看系统报错日志等同于&#xff1a;sudo dmesg -T | grep "(java)"netstat -lnt | grep 590*查看端口状态 nets…

IOS问题汇总:2012-12-18 UIAlertView+UIActionSheet

UIAlertView/UIActionSheet UIAlertView * alertView [[UIAlertView alloc] initWithTitle:“添加场景模式” message:“请输入场景名称” delegate:self cancelButtonTitle:“取消” otherButtonTitles:“确定”, nil];alertView.alertViewStyle UIAlertViewStylePlainTextI…

PHP入门 1 phpstudy安装与配置站点

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1&#xff0c; 一键安装 phpstudy &#xff1b; 点击跳转下载&#xff1b; 2.配置站点&#xff0c;点击MySQL 其它选项菜单的站点域名管理&#xff1b;再点击新增 2&#xff0c;点击其他选项菜单点击打开…

singleton设计模式_让我们研究一下Singleton设计模式的优缺点

singleton设计模式by Navdeep Singh通过Navdeep Singh 让我们研究一下Singleton设计模式的优缺点 (Let’s examine the pros and cons of the Singleton design pattern) Design patterns are conceptual tools for solving complex software problems. These patterns are si…