onilink_

Signal / Slots

Nov 16th, 2015
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #ifndef ONIDEV_UI_SIGNAL_H_INCLUDED
  2. #define ONIDEV_UI_SIGNAL_H_INCLUDED
  3.  
  4. #include <functional>
  5. #include "signal.incl"
  6.  
  7. template <typename... Args>
  8. class Signal
  9. {
  10.     // http://stackoverflow.com/questions/21192659/variadic-templates-and-stdbind
  11.     template<class T, int... Is>
  12.     void connect_member(void (T::*field)(Args...), T* t, int_sequence<Is...>)
  13.     {
  14.         _slot = std::bind(field, t, placeholder_template<Is>{}...);
  15.     }
  16.    
  17. public:
  18.     typedef std::function<void(Args...)> Slot;
  19.    
  20.     template<class T>
  21.     void connect(void (T::*field)(Args...), T* t)
  22.     {
  23.         connect_member(field, t, make_int_sequence<sizeof...(Args)>{});
  24.     }
  25.     void connect(Slot const& slot) const
  26.     {
  27.         _slot = slot;
  28.     }
  29.     void disconnect() const
  30.     {
  31.         _slot = Slot();
  32.     }
  33.     void emit(Args... p)
  34.     {
  35.         if(_slot)
  36.             _slot(p...);
  37.     }
  38.     Signal& operator=(Signal const& other)
  39.     {
  40.         disconnect();
  41.     }
  42.  
  43. private:
  44.     mutable Slot _slot;
  45. };
  46.  
  47. #endif
  48.  
  49.  
  50. --- signal.incl ---
  51.  
  52. #include <cstddef>
  53. #include <type_traits>
  54.  
  55. template<int...>
  56. struct int_sequence
  57. {
  58. };
  59.  
  60. template<int N, int... Is>
  61. struct make_int_sequence:
  62.     make_int_sequence<N-1, N-1, Is...>
  63. {
  64. };
  65. template<int... Is>
  66. struct make_int_sequence<0, Is...>:
  67.     int_sequence<Is...>
  68. {
  69. };
  70.  
  71. template<int>
  72. struct placeholder_template
  73. {
  74. };
  75.  
  76. namespace std
  77. {
  78. template<int N>
  79. struct is_placeholder< placeholder_template<N> >
  80.     : integral_constant<int, N+1>
  81. {
  82. };
  83. }
Advertisement
Add Comment
Please, Sign In to add comment