-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathboost_observer.cpp
More file actions
49 lines (36 loc) · 852 Bytes
/
boost_observer.cpp
File metadata and controls
49 lines (36 loc) · 852 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <boost/signals2.hpp>
#include <iostream>
#include <string>
using namespace boost::signals2;
using namespace std;
template <typename T> struct Observable {
signal<void(T &, const string &)> field_changed;
};
class Person : public Observable<Person> {
int age{0};
public:
Person() {}
explicit Person(int age) : age(age) {}
int get_age() const { return age; }
void set_age(int age) {
if (this->age == age)
return;
this->age = age;
field_changed(*this, "age");
}
};
int main() {
Person p;
// subscribe
auto conn =
p.field_changed.connect([](const Person &p, const string &field_name) {
cout << field_name << " has changed to: " << p.get_age() << endl;
});
p.set_age(18);
p.set_age(19);
p.set_age(20);
// unsubscribe
conn.disconnect();
p.set_age(21);
return 0;
}