BOOST::Signals2

 

  1. /* 
  2. Andy is going to hold a concert while the time is not decided. 
  3. Eric is a fans of Andy who doesn't want to miss this concert. 
  4. Andy doesn't know Eric. 
  5. How can Eric gets the news when Andy's concert is going to take? 
  6. */  
  7. /* 
  8. Singer:被观察者 
  9. Fans:观察者 
  10. */  
  11. #include "stdafx.h"  
  12. #include <iostream>  
  13. #include <boost/signals2.hpp>  
  14. #include <boost/bind.hpp>  
  15. #include <string>  
  16. using namespace std;  
  17. struct Singer  
  18. {  
  19. //定义信号的类型,也就是说 Singer 需要知道 Fans 的响应方式  
  20. //也就是说 Singer 需要知道 Fans 会采用什么样的方式来响应 Singer 所发出的信号  
  21. //或者说 Singer 需要知道 Fans 用什么样的方式来接受 Singer 发出的信号  
  22. //就相当于 Singer 需要知道 Fans的“邮箱”,到时候才可以将信息投递到 Fans 的“邮箱”类型中去  
  23. //Fans 的“邮箱”类型—— void (string time)  
  24.     typedef boost::signals2::signal<void (string time)> signalType;  
  25.     typedef signalType::slot_type slotType;  
  26.     signalType m_signal; //定义一个信号  
  27.       
  28. //Singer 发布信号  
  29.     void PublishTime(string time)  
  30.     {  
  31.         m_signal(time); //将包含 time 信息的信号m_signal投递到 Fans 的邮箱中去,注意,投递之前这种类型的邮箱必须要和一个具体的Fans联系起来,即必须知道是谁拥有这种类型的邮箱,这一动作通过后边的Subscribe实现。  
  32.     }  
  33. //Singer 提供一种注册渠道:Fans们可以通过这个渠道来进行注册,告诉Singer,有新信号的话就发送给我一个消息  
  34.     boost::signals2::connection Subscribe(const slotType& fans)  
  35.     {//在这里将Fans与Singer建立起一种联系(connection)  
  36.     //到后面可以发现,Fans需要调用这个函数,即通过这个渠道告诉Singer有消息就要通知给我  
  37.         return m_signal.connect(fans);  
  38.     }  
  39. };  
  40. struct Fans  
  41. {  
  42. // m_connection:联系的存在是在整个Fans的生命周期内的,一旦Fans消失,这种联系也就不复存在了  
  43.     boost::signals2::scoped_connection m_connection;  
  44. //Fans的响应方式,也就是Fans的邮箱类型,至于里面具体做什么事情,Singer不需要知道。  
  45.     void Correspond(string time)  
  46.     {  
  47.         cout<<"I know the concert time: "<<time<<endl;  
  48.     }  
  49.     //Fans需要自己确定他要关注(观察)哪一个Singer 的动向  
  50.     void Watch(Singer& singer)  
  51.     {  
  52. //通过调用Singer的Subscribe函数(渠道)来将自己的邮箱地址告知Singer  
  53.         m_connection = singer.Subscribe(boost::bind(&Fans::Correspond, this, _1));  
  54.     }  
  55. };  
  56. int main(int argc, char* argv[])  
  57. {  
  58.     Singer  Andy; //刘德华  
  59.     Fans    Eric; //Eric  
  60.     Eric.Watch(Andy); //Eric告知刘德华:我要关注你的动向,请把你的最新信息发给我  
  61.     Andy.PublishTime("2010/10/01");//刘德华发布最新信息,一旦信息发布,Eric的邮箱——void Correspond(string time)就会接受到信息,并进行响应——cout<<….  
  62.     return 0;  
  63. }  
 

Reference:

http://www.cppprog.com/boost_doc/doc/html/signals2/tutorial.html

http://www.cppprog.com/2009/0430/111.html

http://www.cppprog.com/boost_doc/

原文地址:https://www.cnblogs.com/lvdongjie/p/4452063.html