Chinaunix首页 | 论坛 | 博客
  • 博客访问: 885211
  • 博文数量: 254
  • 博客积分: 5350
  • 博客等级: 大校
  • 技术积分: 2045
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 13:27
文章分类

全部博文(254)

文章存档

2015年(1)

2014年(9)

2013年(17)

2012年(30)

2011年(150)

2010年(17)

2009年(28)

2008年(2)

分类: LINUX

2013-07-24 11:38:10


点击(此处)折叠或打开

  1. /*
  2.  * function.cpp
  3.  *
  4.  * Created on: 2013-7-22
  5.  * Author: root
  6.  */
  7. /*
  8. #include <iostream>
  9. #include "boost/function.hpp"

  10. bool some_func(int i,double d)
  11. {
  12.     return i > d;
  13. }

  14. int main()
  15. {
  16.     boost::function<bool (int,double)>f;
  17.     f = &some_func;

  18.     f(10,1.1);
  19. }
  20. */

  21. #include <iostream>
  22. #include <vector>
  23. #include <algorithm>
  24. #include "boost/function.hpp"

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

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

  31. //class notifier {
  32. //    typedef void (*function_type)(int);
  33. //    std::vector<function_type> vec_;
  34. //    int value_;
  35. //public:
  36. //    void add_observer(function_type t) {
  37. //        vec_.push_back(t);
  38. //    }
  39. //
  40. //    void change_value(int i){
  41. //        value_ = i;
  42. //        for(std::size_t i=0; i<vec_.size(); ++i) {
  43. //            (*vec_[i])(value_);
  44. //        }
  45. //    }
  46. //};
  47. //改进后的类,支持对象,指针,boost::function实例
  48. class notifier {
  49.     typedef boost::function<void (int)>function_type;
  50.     std::vector<function_type> vec_;
  51.     int value_;
  52. public:
  53.     template <typename T> void add_observer(T t) {
  54.         vec_.push_back(function_type(t));
  55.     }

  56.     void change_value(int i){
  57.         value_ = i;
  58.         for(std::size_t i=0; i<vec_.size(); ++i) {
  59.             vec_[i](value_);
  60.         }
  61.     }
  62. };

  63. class knows_the_previous_value{
  64.     int last_value_;
  65. public:
  66.     void operator()(int i) {
  67.         static bool first_time = true;
  68.         if(first_time) {
  69.             last_value_ = i;
  70.             std::cout << "This is the first change of value, \
  71.             so I don't know the previous one.\n";
  72.             first_time = false;
  73.             return;
  74.         }
  75.         std::cout << "Previous value was " << last_value_ << '\n';
  76.         last_value_ = i;
  77.     }
  78. };
  79. /*
  80. int main() {
  81.     notifier n;
  82.     n.add_observer(&print_new_value);
  83.     n.add_observer(&interested_in_the_change);
  84.     n.add_observer(knows_the_previous_value()); //使用带状态(参数)的对象是这个功能的亮点

  85.     n.change_value(42);
  86.     std::cout << "\n";
  87.     n.change_value(30);
  88. }
  89. */

阅读(1530) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~