kDB: Knowledge DataBase
Loading...
Searching...
No Matches
MonitoredValue.h
1#include <functional>
2
3#include <QMutex>
4
5namespace knowCore
6{
7 template<typename _T_>
8 class MonitoredValueController;
14 template<typename _T_>
16 {
17 friend class MonitoredValueController<_T_>;
18 MonitoredValue(const _T_& _init) : d(new Private{{}, _init, 0, {}}) {}
19 public:
20 MonitoredValue(const MonitoredValue& _rhs);
21 MonitoredValue& operator=(const MonitoredValue& _rhs);
24 _T_ value() const;
26 std::size_t addMonitor(const std::function<void(const _T_& _value)>& _function);
27 void removeMonitor(std::size_t _idx);
28 private:
29 struct Private
30 {
31 QMutex m;
32 _T_ value;
33 std::size_t nextId;
34 QMap<std::size_t, std::function<void(const _T_& _value)>> monitors;
35 };
37 };
38
39 template<typename _T_>
41 {
42 }
43
44 template<typename _T_>
45 MonitoredValue<_T_>& MonitoredValue<_T_>::operator=(const MonitoredValue& _rhs)
46 {
47 d = _rhs.d;
48 return *this;
49 }
50
51 template<typename _T_>
52 MonitoredValue<_T_>::~MonitoredValue()
53 {
54 }
55
56 template<typename _T_>
58 {
59 return d->value;
60 }
61
62 template<typename _T_>
63 std::size_t
64 MonitoredValue<_T_>::addMonitor(const std::function<void(const _T_& _value)>& _function)
65 {
66 QMutexLocker l(&d->m);
67 std::size_t id = d->nextId++;
68 d->monitors[id] = _function;
69 return id;
70 }
71
72 template<typename _T_>
73 void MonitoredValue<_T_>::removeMonitor(std::size_t _idx)
74 {
75 QMutexLocker l(&d->m);
76 d->monitors.remove(_idx);
77 }
78
85 template<typename _T_>
87 {
88 public:
89 MonitoredValueController(const _T_& _initial_value);
92 void setValue(const _T_& _value);
93 MonitoredValue<_T_> value() const;
94 private:
95 MonitoredValue<_T_> m_value;
96 };
97
98 template<typename _T_>
100 : m_value(_initial_value)
101 {
102 }
103
104 template<typename _T_>
105 MonitoredValueController<_T_>::~MonitoredValueController()
106 {
107 }
108
109 template<typename _T_>
111 {
112 QMutexLocker l(&m_value.d->m);
113 m_value.d->value = _value;
114 for(const std::function<void(const _T_&)>& monitor : m_value.d->monitors)
115 {
116 monitor(_value);
117 }
118 }
119
120 template<typename _T_>
122 {
123 return m_value;
124 }
125} // namespace knowCore
Definition Forward.h:12
Definition Forward.h:6
Definition MonitoredValue.h:87
void setValue(const _T_ &_value)
Set the value and trigger the monitors.
Definition MonitoredValue.h:110
Definition MonitoredValue.h:16
std::size_t addMonitor(const std::function< void(const _T_ &_value)> &_function)
Add a monitor, which is called when the value is changed by the controller.
Definition MonitoredValue.h:64
_T_ value() const
Definition MonitoredValue.h:57