c++超级好用的回调signal slot

2160阅读 0评论2018-09-13 帅得不敢出门
分类:C/C++

用过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


上一篇:编译tina3.0问题及解决
下一篇:c++ 容器中管理存放继承类对象的智能指针