CPP-TOOLBOX
Loading...
Searching...
No Matches
observable.hpp
Go to the documentation of this file.
1#ifndef OBSERVABLE_HPP
2#define OBSERVABLE_HPP
3
4#include <functional>
5#include <vector>
6
7template <typename T> class Observable {
8 public:
9 using Callback = std::function<void(const T &new_value)>;
10
11 Observable() = default;
12 Observable(const T &value) : value(value) {}
13 Observable(T &&value) : value(std::move(value)) {}
14
15 Observable &operator=(const T &new_value) {
16 value = new_value;
17 notify();
18 return *this;
19 }
20
21 Observable &operator=(T &&new_value) {
22 value = std::move(new_value);
23 notify();
24 return *this;
25 }
26
27 void set(const T &new_value) { *this = new_value; }
28
29 void set(T &&new_value) { *this = std::move(new_value); }
30
31 const T &get() const { return value; }
32
33 operator const T &() const { return value; }
34
35 // Add a new observer callback
36 void add_observer(Callback cb) { observers.push_back(std::move(cb)); }
37
38 private:
39 T value;
40 std::vector<Callback> observers;
41
42 void notify() {
43 for (const auto &cb : observers) {
44 cb(value);
45 }
46 }
47};
48
49#endif // OBSERVABLE_HPP
void set(const T &new_value)
Definition observable.hpp:27
const T & get() const
Definition observable.hpp:31
Observable & operator=(T &&new_value)
Definition observable.hpp:21
Observable & operator=(const T &new_value)
Definition observable.hpp:15
void add_observer(Callback cb)
Definition observable.hpp:36
Observable(const T &value)
Definition observable.hpp:12
Observable()=default
Observable(T &&value)
Definition observable.hpp:13
std::function< void(const T &new_value)> Callback
Definition observable.hpp:9
void set(T &&new_value)
Definition observable.hpp:29
@ T
Definition input_state.hpp:73
Definition hashing.hpp:8