1 | // Observable Library |
2 | // Copyright (c) 2016 David Capello |
3 | // |
4 | // This file is released under the terms of the MIT license. |
5 | // Read LICENSE.txt for more information. |
6 | |
7 | #ifndef OBS_OBSERVERS_H_INCLUDED |
8 | #define OBS_OBSERVERS_H_INCLUDED |
9 | #pragma once |
10 | |
11 | #include "obs/safe_list.h" |
12 | |
13 | namespace obs { |
14 | |
15 | template<typename T> |
16 | class observers { |
17 | public: |
18 | typedef T observer_type; |
19 | typedef safe_list<observer_type> list_type; |
20 | typedef typename list_type::iterator iterator; |
21 | |
22 | bool empty() const { return m_observers.empty(); } |
23 | std::size_t size() const { return m_observers.size(); } |
24 | |
25 | void add_observer(observer_type* observer) { |
26 | m_observers.push_back(observer); |
27 | } |
28 | |
29 | void remove_observer(observer_type* observer) { |
30 | m_observers.erase(observer); |
31 | } |
32 | |
33 | template<typename ...Args> |
34 | void notify_observers(void (observer_type::*method)(Args...), Args ...args) { |
35 | for (auto observer : m_observers) { |
36 | if (observer) |
37 | (observer->*method)(std::forward<Args>(args)...); |
38 | } |
39 | } |
40 | |
41 | private: |
42 | list_type m_observers; |
43 | }; |
44 | |
45 | } // namespace obs |
46 | |
47 | #endif |
48 | |