Stride Reference Manual  1.0
Subject.h
Go to the documentation of this file.
1 #pragma once
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 #include <functional>
22 #include <map>
23 #include <memory>
24 
25 namespace stride {
26 namespace util {
27 
34 template<typename E>
35 class Subject {
36 public:
37  using EventType = E;
38  using CallbackType = std::function<void(const EventType&)>;
39 
40 public:
41  virtual ~Subject() { unregisterAll(); }
42 
43  template<typename U>
44  void registerObserver(const std::shared_ptr<U>& u, CallbackType f) {
45  m_observers.insert(make_pair(std::static_pointer_cast<const void>(u), f));
46  }
47 
48  template<typename U>
49  void unregister(const std::shared_ptr<U>& u) {
50  m_observers.erase(std::static_pointer_cast<const void>(u));
51  }
52 
53  void unregisterAll() {
54  m_observers.clear();
55  }
56 
57  void notify(const EventType& e) {
58  for (const auto& o : m_observers) {
59  const auto spt = o.first.lock();
60  if (spt) {
61  (o.second)(e);
62  } else {
63  m_observers.erase(o.first);
64  }
65  }
66  }
67 
68 private:
69  std::map<std::weak_ptr<const void>, CallbackType, std::owner_less<std::weak_ptr<const void>>> m_observers;
70 };
71 
72 }
73 }
void unregister(const std::shared_ptr< U > &u)
Definition: Subject.h:49
void registerObserver(const std::shared_ptr< U > &u, CallbackType f)
Definition: Subject.h:44
Time Dependent Person DataType.
Definition: NoBehaviour.h:17
void unregisterAll()
Definition: Subject.h:53
std::function< void(const EventType &)> CallbackType
Definition: Subject.h:38
void notify(const EventType &e)
Definition: Subject.h:57
Main class that contains and direct the virtual world.
Definition: Simulator.h:64
Template for Subject/Observer (or Publish/Subscribe).
Definition: Subject.h:35
std::map< std::weak_ptr< const void >, CallbackType, std::owner_less< std::weak_ptr< const void > > > m_observers
Definition: Subject.h:69
virtual ~Subject()
Definition: Subject.h:41