现在的位置: 首页 > 综合 > 正文

Boost之function

2018年02月16日 ⁄ 综合 ⁄ 共 1458字 ⁄ 字号 评论关闭

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();
}

【上篇】
【下篇】

抱歉!评论已关闭.