Chinaunix首页 | 论坛 | 博客
  • 博客访问: 496844
  • 博文数量: 111
  • 博客积分: 3160
  • 博客等级: 中校
  • 技术积分: 1982
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-24 11:49
个人简介

低调、勤奋。

文章分类

全部博文(111)

文章存档

2014年(2)

2013年(26)

2012年(38)

2011年(18)

2010年(27)

分类: C/C++

2014-02-21 14:33:47

boost function相当于函数指针,通过bind函数去绑定一个函数和一个对象以及参数。

如:
boost::function f1; // 此处参数为空,返回值为空
boost::function f2; //此处参数为int和string,返回值类型为int

class Foo
{
 public:
  void methodA();
  void methodInt(int a);
};
class Bar
{
 public:
  void methodB();
};

Foo foo;
f1 = boost::bind(&Foo::methodA, &foo);
f1(); // 调用 foo.methodA();
Bar bar;
f1 = boost::bind(&Bar::methodB, &bar);
f1(); // 调用 bar.methodB();

f1 = boost::bind(&Foo::methodInt, &foo, 42);
f1(); // 调用 foo.methodInt(42);

boost::function f2; // int 参数,无返回值
f2 = boost::bind(&Foo::methodInt, &foo, _1);
f2(53); // 调用 foo.methodInt(53);


点击(此处)折叠或打开

  1. #include <boost/function.hpp>
  2. #include <boost/bind.hpp>
  3. #include <iostream>

  4. using namespace std;


  5. class TestA
  6. {
  7.     public:
  8.         void method()
  9.         {
  10.             cout<<"TestA: method: no arguments"<<endl;
  11.         }

  12.         void method(int a, int b)
  13.         {
  14.             cout<<"TestA: method: with arguments"
  15.                 <<"value of a is: "<<a
  16.                 <<" value of b is  "<<b <<endl;
  17.         }
  18. };


  19. void sum(int a, int b)
  20. {
  21.     int sum = a + b;
  22.     cout<<"sum: "<<sum<<endl;
  23. }

  24. int main()
  25. {
  26.     boost::function<void()> f;
  27.     boost::function<void(int, int)> e;
  28.     TestA test;

  29.     f = boost::bind(&TestA::method, &test);
  30.     f();

  31.     f = boost::bind(&TestA::method, &test, 1, 2);
  32.     f();

  33.     e = boost::bind(&TestA::method, &test, 1, _2); //注意如果参数前面加了下划线,则表示该参数可以替换。
  34.     e(3,5);

  35.     f = boost::bind(&sum, 1, 2);
  36.     f();
  37. }
打印值:
TestA: method: no arguments
TestA: method: with argumentsvalue of a is: 1 value of b is 2
TestA: method: with argumentsvalue of a is :1 value of b is 5
sum: 3



阅读(1649) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~