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;
}

 

原创粉丝点击