Radium Engine  1.5.20
Loading...
Searching...
No Matches
Observable.hpp
1#pragma once
2
3#include <Core/Utils/Log.hpp>
4
5#include <functional>
6#include <map>
7
8namespace Ra {
9namespace Core {
10namespace Utils {
11
31
32template <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
90class RA_CORE_API ObservableVoid : public Observable<>
91{};
92
93} // namespace Utils
94} // namespace Core
95} // namespace Ra
int attach(Observer observer)
Observable()=default
Default constructor ... do nothing ;)
void detachAll()
Detach all observers.
void notify(Args... p) const
Notify (i.e. call) each attached observer with argument p.
void detach(int observerId)
int attachMember(T *object, void(T::*observer)(Args...))
void copyObserversTo(Observable &other) const
explicit copy of all attached observers the other Observable
T forward(T... args)
hepler function to manage enum as underlying types in VariableSet
Definition Cage.cpp:3