【Boost】boost::function介绍

转自:http://blog.csdn.net/huang_xw/article/details/8249278


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.例子

#include<iostream>
#include<boost/function.hpp>
using namespace std;
int fsum(int i, int j)
{
    return i + j;
}

class Person
{
public:
    void operator() (std::string name, int age)
    {
    std::cout << name << ": " << age << std::endl;
    }
};
        
class Car
{
public:
  Car(){}
  virtual ~Car(){}
  void info(int i)
  {
     std::cout << "info = " << i << std::endl;
  }
};
        
void test_function()
{
// 1. 普通函数
  boost::function<int(int, int)> func1;
  func1 = fsum;
  std::cout << "4 + 5 = " << func1(4, 5) << std::endl;
    
// 2. 函数对象
  boost::function<void(std::string, int)> func2;
  Person person;
  func2 = person;
  func2("myname", 30);
          
  // 3. 成员函数
  boost::function<void(Car*, int)> func3;
  func3 = &Car::info;
  Car car;
  func3(&car, 25);
  
  // 4. 空函数
  boost::function<int(int, int)> func4;
  assert(func4.empty());
  assert(!func1.empty());
  func1.clear();
  assert(func1.empty());
  try
  {
      func1(4, 5);
  }
  catch (std::exception& e)
  {
      std::cout << e.what() << std::endl;
  }
}
int main()
{
    test_function();
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值