Boost之function

本文介绍了如何使用Boost库中的函数指针实现回调机制,并通过示例展示了如何为不同的观察者添加不同的回调函数来响应特定事件。

function是Boost的函数指针。

//回调函数对象
#include <iostream>
#include <vector>
#include "boost/function.hpp"

class notifier {
  typedef boost::function<void(int)> function_type;
  std::vector<function_type> vec_;
  int value_;
public:
  template <typename T> void add_observer(T t) {
    vec_.push_back(function_type(t));
  }

  void change_value(int i) {
    value_=i;
    for (std::size_t i=0;i<vec_.size();++i) {
      vec_[i](value_);
    }
  }
};

class knows_the_previous_value {
  int last_value_;
public:
  void operator()(int i) {
    static bool first_time=true;
    if (first_time) {
      last_value_=i;
      std::cout << 
        "This is the first change of value, \
so I don't know the previous one.\n";
      first_time=false;
      return;
    }
    std::cout << "Previous value was " << last_value_ << '\n';
    last_value_=i;
  }
};

void print_new_value(int i) {
  std::cout << 
    "The value has been updated and is now " << i << '\n';
}

void interested_in_the_change(int i) {
  std::cout << "Ah, the value has changed.\n";
}


int main() {
  notifier n;
  n.add_observer(&print_new_value);
  n.add_observer(&interested_in_the_change);
  n.add_observer(knows_the_previous_value());

  n.change_value(42);
  std::cout << '\n';
  n.change_value(30);

  std::cin.get();
}

//回调类成员
#include <iostream>
#include <vector>
#include "boost/function.hpp"

class some_class {
public:
  void do_stuff(int i) const {
    std::cout << "OK. Stuff is done. " << i << '\n';
  }
};

int main() {

	//传值
	boost::function<void(some_class,int)> f1;
	f1=&some_class::do_stuff;
	f1(some_class(),1);
	//传引用
	boost::function<void(some_class&,int)> f2;
	f2=&some_class::do_stuff;
	some_class s;
	f2(s,2);
	//传指针
	boost::function<void(some_class*,int)> f3;
	f3=&some_class::do_stuff;
	f3(&s,3);

  std::cin.get();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值