c++11 对std::function与std::bind理解
来源:互联网 发布:mac电脑自带抠图软件 编辑:程序博客网 时间:2024/05/19 16:36
std::function
和 std::bind
的问世,替代了 Boost C++ 库,他们被纳入c++11新标准。使用它们可以实现类似函数指针的功能,但却却比函数指针更加灵活,特别是函数指向类 的非静态成员函数时。std::function可以绑定到全局函数/类静态成员函数
(类静态成员函数与全局函数没有区别),如果要绑定到类的非静态成员函数,则需要使用std::bind
一、对std::function和std::bind理解与运用
#include <iostream>
#include <functional>
using namespace std;
typedef std::function<void ()> fp;
void g_fun()
{
cout<<"g_fun()"<<endl;
}
class A
{
public:
static void A_fun_static()
{
cout<<"A_fun_static()"<<endl;
}
void A_fun()
{
cout<<"A_fun()"<<endl;
}
void A_fun_int(int i)
{
cout<<"A_fun_int() "<<i<<endl;
}
//非静态类成员,因为含有this指针,所以需要使用bind
void init()
{
fp fp1=std::bind(&A::A_fun,this);
fp1();
}
void init2()
{
typedef std::function<void (int)> fpi;
//对于参数要使用占位符 std::placeholders::_1
fpi f=std::bind(&A::A_fun_int,this,std::placeholders::_1);
f(5);
}
};
int main()
{
//绑定到全局函数
fp f2=fp(&g_fun);
f2();
//绑定到类静态成员函数
fp f1=fp(&A::A_fun_static);
f1();
A().init();
A().init2();
return 0;
}
二、cocos2dx 3.0对std::bind运用
auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose,std::bind(&HelloWorld::closeCallback,this));
void HelloWorld::closeCallback(Ref * sender)
{
exit(0);
}
其中std::bind(&HelloWorld::closeCallback,this)可以用cocos2dx-3.0中定义的宏来替换例如:
CC_CALLBACK_1(TestController::closeCallback, this)
小小的总结下:CC_CALLBACK0是回调不带参数的回调函数,CC_CALLBACK1带一个参数的回调函数。
- c++11 对std::function与std::bind理解
- std::function std::bind理解
- C++11 std::bind与std::function
- c++11 std::bind与std::function
- std::bind与std::function
- std::function std::bind
- std::function std::bind
- c++11 特性 std::function 与 std::bind
- C++11新特性之std::bind与std::function
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- std::function与std::bind 函数指针
- 新辰:河南工业90后被称”破烂王” 创业3年盈利15万
- jquery 瀑布流原理 页面到达底部加载数据的方法
- 数字签名是什么?
- 哈夫曼树及哈夫曼编码
- 单词数
- c++11 对std::function与std::bind理解
- matlab调用opencv
- ubuntu 14.04 搭建Android开发环境
- F5的会话保持
- MySQL 获得当前日期时间(以及时间的转换)
- ORA-01200的简单处理
- 代码测试、调试、优化相关知识
- UTF-8 Unicode是如何转换的
- linux系统监控命令