Stride Reference Manual  - generated for commit 9643b11
util/Subject.h
Go to the documentation of this file.
1 
2 /*
3  * Copyright 2011-2016 Universiteit Antwerpen
4  *
5  * Licensed under the EUPL, Version 1.1 or as soon they will be approved by
6  * the European Commission - subsequent versions of the EUPL (the "Licence");
7  * You may not use this work except in compliance with the Licence.
8  * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl5
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the Licence is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the Licence for the specific language governing
14  * permissions and limitations under the Licence.
15  */
21 #pragma once
22 
23 #include <functional>
24 #include <map>
25 #include <memory>
26 
27 namespace stride {
28 namespace util {
29 
36 template <typename E>
37 class Subject
38 {
39 public:
40  using EventType = E;
41  using CallbackType = std::function<void(const EventType&)>;
42 
43 public:
45 
46  virtual ~Subject() { UnregisterAll(); }
47 
48  template <typename U>
49  void Register(const std::shared_ptr<U>& u, CallbackType f)
50  {
51  m_observers.insert(make_pair(std::static_pointer_cast<const void>(u), f));
52  }
53 
54  template <typename U>
55  void Unregister(const std::shared_ptr<U>& u)
56  {
57  m_observers.erase(std::static_pointer_cast<const void>(u));
58  }
59 
60  void UnregisterAll() { m_observers.clear(); }
61 
62  void Notify(const EventType& e)
63  {
64  for (const auto& o : m_observers) {
65  const auto spt = o.first.lock();
66  if (spt) {
67  (o.second)(e);
68  } else {
69  m_observers.erase(o.first);
70  }
71  }
72  }
73 
74 private:
75  std::map<std::weak_ptr<const void>, CallbackType, std::owner_less<std::weak_ptr<const void>>> m_observers;
76 };
77 
78 } // namespace util
79 } // namespace stride
std::function< void(const EventType &)> CallbackType
Definition: util/Subject.h:41
Id
Enumerates the event.
Definition: Id.h:30
void Notify(const EventType &e)
Definition: util/Subject.h:62
std::map< std::weak_ptr< const void >, CallbackType, std::owner_less< std::weak_ptr< const void > > > m_observers
Definition: util/Subject.h:75
void Unregister(const std::shared_ptr< U > &u)
Definition: util/Subject.h:55
void Register(const std::shared_ptr< U > &u, CallbackType f)
Definition: util/Subject.h:49
Namespace for the simulator and related classes.
Definition: Calendar.cpp:28
Template for Subject/Observer (or Publish/Subscribe).
Definition: util/Subject.h:37