Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4463502
  • 博文数量: 356
  • 博客积分: 10458
  • 博客等级: 上将
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-24 14:59
文章分类

全部博文(356)

文章存档

2020年(17)

2019年(9)

2018年(26)

2017年(5)

2016年(11)

2015年(20)

2014年(2)

2013年(17)

2012年(15)

2011年(4)

2010年(7)

2009年(14)

2008年(209)

分类: C/C++

2018-09-13 14:58:53

用过Qt的应该都知道,signal  slot,用来做解耦及回调超级好用,如果没有Qt怎么办,可以用c++11的功能实现,
当然网络上已经有许多实现,可以直接用的。
比如:

示例代码:

  1. // Using Delegate.h
  2.  
  3. void MyFunc( int x )
  4. {
  5.     printf( "MyFunc( %d )", x );
  6. }
  7.  
  8.  
  9. // Using Signal.h
  10.  
  11. class Button
  12. {    
  13. public:
  14.     Signal2< int, float > updateLabel;
  15.  
  16.     void Click( void )
  17.     {
  18.         updateLabel( 2, 34.5 );
  19.     }
  20. };
  21.  
  22. class Label
  23. {
  24. public:
  25.     virtual void Update( int i, float f )
  26.     {
  27.         printf( "Update( %d, %.1f )", i, f );
  28.     }
  29. };
  30.  
  31. int main()
  32. {
  33.     Delegate1< int > delegate;
  34.     delegate.Bind( & MyFunc );
  35.     delegate( 5 );
  36.  
  37.     Button myButton;
  38.     Label myLabel1;
  39.     Label myLabel2;
  40.     myButton.updateLabel.Connect( & myLabel1, & Label::Update );
  41.     myButton.updateLabel.Connect( & myLabel2, & Label::Update );
  42.     myButton.Click();
  43.  
  44.     return 0;
  45. }
是不是很方便,其他的项目:




这里其实还有一个需求,像qt一样,回调可以指定绑定到sender还是reciver的线程中去执行,这种需要调用回调的代码那里修改实现,简单看了下描述,好像上面几个实现没有这个功能. 还有一种是自建线程执行,最后这种方式实现比较简单。
作者:帅得不敢出门    c++哈哈堂:31843264


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