std::function与std::bind 函数指针
来源:互联网 发布:linux ant使用教程 编辑:程序博客网 时间:2024/06/05 06:01
std::function与std::bind 函数指针
分类: cpp2013-01-22 20:37 26330人阅读 评论(5) 收藏 举报
function模板类和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;
- }
同时,std::bind绑定到虚函数时会表现出多态行为。
- #include <iostream>
- #include <functional>
- using namespace std;
- typedef std::function<void ()> fp;
- class A
- {
- public:
- virtual void f()
- {
- cout<<"A::f()"<<endl;
- }
- void init()
- {
- //std::bind可以表现出多态行为
- fp f=std::bind(&A::f,this);
- f();
- }
- };
- class B:public A
- {
- public:
- virtual void f()
- {
- cout<<"B::f()"<<endl;
- }
- };
- int main()
- {
- A* pa=new B;
- pa->init();
- return 0;
- }
0 0
- 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 函数指针
- 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 函数指针
- 【cocos2dx】std::function与std::bind 函数指针
- Android在ListView显示图片(重复错乱闪烁问题)
- 编程用 JAVA 解析 XML 的方式。
- ARM 指令集
- Solr 5.2 环境搭建
- Java线程(六):线程池
- std::function与std::bind 函数指针
- RMAN 备份异机恢复 并创建新DBID
- hdoj 1286 找新朋友 【容斥原理 or 欧拉函数 基础题】
- MUI开发实践教程第一集
- win7 两张网卡搭建两个文件服务器
- Ubuntu Server下启动/停止/重启MySQL数据库的三种方式
- Java线程(七):Callable和Future
- 合并两个排序的链表
- e代维需身怀代码绝技的攻城狮