【Boost】boost::function介绍

来源:互联网 发布:电脑windows激活不了 编辑:程序博客网 时间:2024/05/01 19:06
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 plaincopyprint?
  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. }  

转载地址:http://blog.csdn.net/huang_xw/article/details/8249278

0 0
原创粉丝点击