1.bind函数

网络编程中, 经常要使用到回调函数。 当底层的网络框架有数据过来时,往往通过回调函数来通知业务层。 这样可以使网络层只专注于 数据的收发, 而不必关心业务

在c语言中, 回调函数的实现往往通过函数指针来实现。 但是在c++中 , 如果回调函数是一个类的成员函数。这时想把成员函数设置给一个回调函数指针往往是不行的

因为类的成员函数,多了一个隐含的参数this。 所以直接赋值给函数指针肯定会引起编译报错

c++11 为我们带来了bind, 可以很好的解决这个问题

include

std::bind(待绑定的函数对象/函数指针/成员函数指针,参数绑定值1,参数绑定值2,...,参数绑定值n);

2.bind用法

1.普通函数
#include <iostream>
#include <memory>
#include <functional> using namespace std; void fun1(int n1, int n2, int n3)
{
cout << n1 << " " << n2 << " " << n3 << endl;
} int main()
{
//原fun1接受三个参数,其中绑定了2个,第三个参数由新的可调用对象指定
auto f1 = bind(fun1, 11, 22, placeholders::_1);
f1(33);
} 运行结果是:11 22 33
2.普通函数与_1,_2;
#include <iostream>
#include <memory>
#include <functional> using namespace std::placeholders;
using namespace std; void fun1(int n1, int n2, int n3)
{
cout << n1 << " " << n2 << " " << n3 << endl;
} int main()
{
//_1表示这个位置是新的可调用对象的第一个参数的位置
//_2表示这个位置是新的可调用对象的第二个参数的位置
auto f1 = bind(fun1, _2, 22, _1);
f1(44,55);
} 运行结果是 55 22 44
3.成员函数
#include <iostream>
#include <memory>
#include <functional> using namespace std::placeholders;
using namespace std; class A
{
public:
void print(int n1, int n2, int n3)
{
cout << n1 << " " << n2 << " " << n3 << endl;
}
}; int main()
{
A a;
//类成员函数需要绑定该类的this指针
auto f1 = bind(&A::print, &a, 22,44,55 );
f1();
}
运行结果: 22,44,55

最新文章

  1. eclipse 突然 一直在loading descriptor for XXX (XXX为工程名)
  2. 如何得到自定义UITableViewCell中的按钮所在的cell的indexPath.row
  3. System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800AC472
  4. iOS七大手势识别
  5. dede让channelartlist标签支持currentstyle属性 完美解决
  6. tmpfs
  7. HTML5 本地裁剪图片
  8. 使用HttpClient进行http post/get方法的调用,以及使用dom4j解析xml
  9. centos 编译安装nginx
  10. Nginx调用远程php-fpm
  11. 使用EasyPOI导出excel示例
  12. c# 获取 com 引用真实组件地址
  13. java对excel文件内容读写修改操作
  14. Python3 pip命令报错:Fatal error in launcher: Unable to create process using &#39;&quot;&#39;
  15. Gitlab用户在组中有五种权限:Guest、Reporter、Developer、Master、Owner
  16. day4-python基础-运算符
  17. LG3187 [HNOI2007]最小矩形覆盖
  18. Linux内核分析第四周总结
  19. 【Android】HAL分析
  20. 利用函数来得到所有子节点号&amp; 利用函数来取得最高级的节点号

热门文章

  1. 1759E(方案枚举)
  2. JqGrid 编辑单元格内容时提示url未设定错误 2018-08-06
  3. Mybatis-plus - ActiveRecord 模式CRUD
  4. jquery操作class
  5. 初始化一个ArrayList的多种方式
  6. 「笔记」某移动SRE运维体系交流
  7. 对象和类—Java世界的细胞
  8. .Net执行SQL/存储过程之易用轻量工具
  9. python 之列表(list)处理
  10. 微信小程序地区和location_id对应关系