Boost.Function

1. 介绍
    Boost.Function库包含了一个类族的函数对象的包装。它的概念很像广义上的回调函数。其有着和函数指针相同的特性但是又包含了一个调用的接口。一个函数指针能够在能以地方被调用或者作为一个回调函数。boost.function能够代替函数指针并提供更大的灵活性。
2. 使用
    Boost.Function有两种形式:boost::function<float(int x, int y)>f
    使用类型: 普通函数, 成员函数, 函数对象。
    使用function时,可以通过empty函数或与0比较来判断其是否指向一个有效的函数。如果function没有指向一个有效的函数,调用时会抛出bad_function_call的异常。function的clear函数可以使其不再关联到一个函数或函数对象,如果该function本身就是空的,调用该函数也不会带来任何问题。
3.例子
[cpp]  view plain  copy
 print ?
  1. int fsum(int i, int j)  
  2. {  
  3.     return i + j;  
  4. }  
  5.   
  6. class Person  
  7. {  
  8. public:  
  9.     void operator() (std::string name, int age)  
  10.     {  
  11.         std::cout << name << ": " << age << std::endl;  
  12.     }  
  13. };  
  14.   
  15. class Car  
  16. {  
  17. public:  
  18.     Car(){}  
  19.     virtual ~Car(){}  
  20.     void info(int i)  
  21.     {  
  22.         std::cout << "info = " << i << std::endl;  
  23.     }  
  24. };  
  25.   
  26. void test_function()  
  27. {  
  28.     // 1. 普通函数  
  29.     boost::function<int(intint)> func1;  
  30.     func1 = fsum;  
  31.     std::cout << "4 + 5 = " << func1(4, 5) << std::endl;  
  32.   
  33.     // 2. 函数对象  
  34.     boost::function<void(std::string, int)> func2;  
  35.     Person person;  
  36.     func2 = person;  
  37.     func2("myname", 30);  
  38.   
  39.     // 3. 成员函数  
  40.     boost::function<void(Car*, int)> func3;  
  41.     func3 = &Car::info;  
  42.     Car car;  
  43.     func3(&car, 25);  
  44.   
  45.     // 4. 空函数  
  46.     boost::function<int(intint)> func4;  
  47.     assert(func4.empty());  
  48.     assert(!func1.empty());  
  49.     func1.clear();  
  50.     assert(func1.empty());  
  51.     try  
  52.     {  
  53.         func1(4, 5);  
  54.     }  
  55.     catch (std::exception& e)  
  56.     {  
  57.         std::cout << e.what() << std::endl;  
  58.     }  
  59. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值