fork(1) download
  1. #include <vector>
  2. #include <iostream>
  3. #include <functional>
  4.  
  5. template<typename ...Params>
  6. struct Publisher
  7. {
  8. using Signature = void( Params... );
  9. using FunctionType = std::function<Signature>;
  10.  
  11. std::vector<FunctionType> Subscribers_;
  12.  
  13. void subscribe( Signature FreeFunc )
  14. {
  15. Subscribers_.emplace_back( FreeFunc );
  16. }
  17.  
  18. template<typename ObjType>
  19. void subscribe( ObjType* Obj, void (ObjType::*MemFun)( Params... ) )
  20. {
  21. Subscribers_.push_back( std::bind( MemFun, Obj,
  22. std::placeholders::_1 ) );
  23. }
  24.  
  25. void operator()( Params&&... p )
  26. {
  27. for( const auto& Sub : Subscribers_ )
  28. {
  29. Sub( std::forward<Params>( p )... );
  30. }
  31. }
  32. };
  33.  
  34. void func1( unsigned int )
  35. {
  36. }
  37.  
  38. void func2( unsigned int& )
  39. {
  40. }
  41.  
  42. void func3( const unsigned int& )
  43. {
  44. }
  45.  
  46. struct Test
  47. {
  48. void func1( unsigned int )
  49. {
  50. }
  51.  
  52. void func2( unsigned int& )
  53. {
  54. }
  55.  
  56. void func3( const unsigned int& )
  57. {
  58. }
  59. };
  60.  
  61. int main()
  62. {
  63. Publisher<unsigned int&> Pub;
  64.  
  65. // Pub.subscribe( &func1 );
  66. Pub.subscribe( &func2 );
  67. // Pub.subscribe( &func3 );
  68.  
  69. Test t;
  70. // Pub.subscribe( &t, &Test::func1 );
  71. Pub.subscribe( &t, &Test::func2 );
  72. // Pub.subscribe( &t, &Test::func3 );
  73.  
  74. unsigned int Arg = 1;
  75. Pub( Arg );
  76. }
  77.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty