boost::function(函数)实现普通函数和类成员函数的回调
来源:互联网 发布:php如何运行 编辑:程序博客网 时间:2024/04/30 09:03
0. boost::function库的功能和目的
boost::function库的主要功能是为后续的调用存储函数指针和函数对象,也就是说事先存储某个函数的原型(包括它的返回类型,参数列表),待到需要的时候再利用存储的函数指针或函数对象进行实际的函数调用。 这种机制传统方式称为回调。个人认为这种功能可以在C++中实现反射的部分功能。例如可以在容器中存储某个领域类的所有成员函数。然后在适当的时候进行调用。
1.用法:
1)首先包含头文件 "boot/function.hpp" 或 "boost/functionX.hpp" (这里X表示函数参数的个数)
2)然后,声明函数类型:共有两种形式,分别为:
A:首选语法声明
boost::function<bool (int) > f;
其中,bool-函数的返回类型, int - 函数的参数类型
B:兼容语法声明
(我的boost1_33_1 VC++ 6.0 好像只支持这种,比较麻烦,因为它要在在function声明时加上参数数目,
不包含返回参数数目,见后面的例子)
boost::function2(void,int,double) f;
3) 赋值(函数对象赋值前为空指针,调用时会产生异常)。
bool some_func(int i,double d)
{
return i>d;
}
f=&some_func;
或
class some_class
{
private:
int ID;
public:
int GetID() { return ID;};
};
f=some_class::GetID;
4) 调用,安照函数的调用法则进行。
f(10,1.0)
2. 普通全局函数的回调
示例代码如下:
#include "boost/function.hpp"
bool some_func(int i,double d)
{
return i>d;
}
int main(int argc, char* argv[])
{
boost::function2<bool,int,double > f;
f = &some_func;
f(10,1.1);
}
3. 类的成员函数的回调
示例代码如下:
#include <iostream>
#include "boost/function.hpp"
using namespace std;
class some_class
{
private:
int ID;
public:
some_class() {};
~some_class() {};
int GetID() { return ID;};
void SetID(int m_ID) { ID = m_ID; };
};
typedef struct createObj
{
some_class* create() {return new some_class();};
}CRO;
int main(int argc, char* argv[])
{
boost::function1<some_class*,CRO*> f_constructor; //
boost::function2<void, some_class*,int > f_set;
boost::function1<int, some_class* > f_get;
f_constructor= &CRO::create; //产生对象实例的函数(我们没法显式调用函数的构造函数,因此采用这种办法)
some_class* ps = f_constructor( new CRO() ) ; // f_constructor函数调用产生som_class对象实例
f_set = &some_class::SetID; // set 函数
f_get = &some_class::GetID; // get 函数
f_set(ps,888); // set 函数调用
cout<< "getID()="<< f_get(ps) <<endl; // get 函数调用
delete ps;
return 0;
}
- boost::function(函数)实现普通函数和类成员函数的回调
- boost::bind boost::function绑定万能函数测试2(类成员函数和虚函数)
- 类的成员函数和普通成员函数的区别
- boost::function 通过boost::bind调用类成员函数
- 静态成员函数和普通成员函数的区别?
- 静态成员函数和普通成员函数的区别
- 静态成员函数和普通成员函数的区别
- 虚函数、普通成员函数访问类的数据成员
- 为什么使用boost::function绑定类成员函数时,类的析构函数不能为虚函数
- 类中的三种函数(普通成员函数、静态成员函数、COSNT成员函数)总结
- 类的普通成员函数的指针
- 类的普通成员函数的指针
- 类的普通成员函数的指针
- 关于成员函数指针和普通函数指针的转换
- 普通类的模板成员函数
- 普通函数和类成员函数const重载
- 普通函数指针和指向成员函数指针(转载)
- 类中虚函数、普通成员函数的调用
- 取得数据库的表里的一行数据
- C#中使用 SendMessage 向非顶端窗体发送组合键
- 面向对象 jQuery编程
- 【转载自天涯】个人开公司需要什么手续,流程,办理要多少时间?
- Vxworks信号量分析
- boost::function(函数)实现普通函数和类成员函数的回调
- 项目心得
- Lib-SVM使用说明
- 开始菜单里的关机命令没有响应
- How to get the file's icon using C++ - 用C++如何获取文件的图标
- 考研成绩第一考上清华研究生的经历
- checkbox赋值function code的区别
- Alter table
- 图片面板(ImagePanel)