boost::function

来源:互联网 发布:mac适合编程吗 编辑:程序博客网 时间:2024/05/01 17:06

boost::function 介绍

    本片文章主要介绍boost::function的用法。 boost::function 就是一个函数的包装器(function wrapper),用来定义函数对象。


    Boost.Function 语法如下:

首选形式 boost::function<float(int x, int y)>f 


2.1 封装普通函数

    我们可以看下如下的例子:

复制代码
1 void do_sum(int *values, int n)
2 {
3 int sum(0);
4 for (int i = 0; i < n; ++i)
5 {
6 sum += values[i];
7 }
8 cout << sum << endl;
9 };
10 int _tmain(int argc, _TCHAR* argv[])
11 {
12 boost::function<void(int *values, int n)> sum;
13 sum = &do_sum;
14 int a[] = {1,2,3,4,5};
15 sum(a, 5);
16 return 0;
17 }
复制代码

  sum 可以理解为一个广义的函数对象了,其只用就是保存函数do_sum, 然后再调用之。


2.2 封装类的成员函数

    在很多系统中, 对于类的成员函数的回调需要做特殊处理的。这个特殊的处理就是“参数绑定”。当然这个超出了我们讨论的范围了。 boost::function对于成员函数的使用可以看下如下代码:

复制代码
1 class X{
2 public:
3 int foo(int a)
4 {
5 cout << a <<endl;
6 return a;
7 }
8 };
9 int _tmain(int argc, _TCHAR* argv[])
10 {
11 boost::function<int(X*, int)>f;//X* 是this指针
12 f = &X::foo;
13 X x;
14 f(&x, 5);
15 return 0;
16 }
复制代码

    我们发现, 对类的成员函数的对象化从语法是没有多大的区别。





===================================================


boost::function就是所谓的仿函数,能够对普通函数指针,成员函数指针,functor进行委托,达到迟调用的效果。

 

其作用主要是对某个类的成员函数进行委托,使该类的这个成员函数像一个普通函数一样使用。

 

#include <boost/function.hpp>
int foo(int x,int y)
{
 cout<< "(foo invoking)x = "<<x << " y = "<< y <<endl;
 return x+y;
}

struct test
{
 int foo(int x,int y)
 {
  cout<< "(test::foo invoking)x = "<<x << " y = "<< y <<endl;
  return x+y;
 }
};

void test_function()
{
 boost::function<int (int,int)> f;//<int (int,int)>为函数的返回值和形参类型,即函数的类型。
 f = foo;//直接使用普通函数
 cout << "f(2,3)="<<f(2,3)<<endl;

 test x;
 boost::function<int (test*,int,int)> f2;//test类中的f成员函数进行包装,使test类中f成员函数看起来像一个普通函数。
 f2 = &test::foo;
  
 cout << "f2(5,3)="<<f2(&x,5,3)<<endl;
}
0 0
原创粉丝点击