Radium Engine  1.5.0
Observable.hpp
1 #pragma once
2 
3 #include <Core/Utils/Log.hpp>
4 
5 #include <functional>
6 #include <map>
7 
8 namespace Ra {
9 namespace Core {
10 namespace Utils {
11 
31 
32 template <typename... Args>
34 {
35  public:
37  using Observer = std::function<void( Args... )>;
38 
40  Observable() = default;
41  Observable( const Observable& ) = delete;
42  Observable& operator=( const Observable& ) = delete;
43  virtual ~Observable() = default;
44 
46  void copyObserversTo( Observable& other ) const {
47  for ( const auto& o : m_observers ) {
48  other.attach( o.second );
49  }
50  }
51 
54  inline int attach( Observer observer ) {
55  m_observers.insert( { ++m_currentId, observer } );
56  return m_currentId;
57  }
58 
62  template <typename T>
63  int attachMember( T* object, void ( T::*observer )( Args... ) ) {
64  return attach( bind( observer, object ) );
65  }
67  inline void notify( Args... p ) const {
68  for ( const auto& o : m_observers )
69  o.second( std::forward<Args>( p )... );
70  }
71 
73  inline void detachAll() { m_observers.clear(); }
74 
77  inline void detach( int observerId ) { m_observers.erase( observerId ); }
78 
79  private:
80  // from https://stackoverflow.com/questions/21192659/variadic-templates-and-stdbind
81  template <typename R, typename T, typename U>
82  std::function<R( Args... )> bind( R ( T::*f )( Args... ), U p ) {
83  return [p, f]( Args... args ) -> R { return ( p->*f )( args... ); };
84  }
85 
86  std::map<int, Observer> m_observers;
87  int m_currentId { 0 };
88 };
89 
90 class RA_CORE_API ObservableVoid : public Observable<>
91 {};
92 
93 } // namespace Utils
94 } // namespace Core
95 } // namespace Ra
int attach(Observer observer)
Definition: Observable.hpp:54
Observable()=default
Default constructor ... do nothing ;)
void detachAll()
Detach all observers.
Definition: Observable.hpp:73
std::function< void(Args...)> Observer
Observer functor type.
Definition: Observable.hpp:37
void notify(Args... p) const
Notify (i.e. call) each attached observer with argument p.
Definition: Observable.hpp:67
void detach(int observerId)
Definition: Observable.hpp:77
int attachMember(T *object, void(T::*observer)(Args...))
Definition: Observable.hpp:63
void copyObserversTo(Observable &other) const
explicit copy of all attached observers the other Observable
Definition: Observable.hpp:46
Definition: Cage.cpp:3