version 0.4.1
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
broadcaster.hh
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2021-2025 The Ikarus Developers mueller@ibb.uni-stuttgart.de
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
9#pragma once
10#include <functional>
11#include <memory>
12#include <vector>
13
14namespace Ikarus {
15
16template <class Args>
18
24template <typename... Args>
25class Broadcaster<void(Args...)>
26{
27 using F = std::function<void(Args...)>;
28
29 // The functions are stored as weak pointer, therefore the Broadcaster has no ownership over them.
30 std::vector<std::weak_ptr<F>> listeners;
31
32public:
33 using Token = std::shared_ptr<F>;
34
45 auto sp = std::make_shared<F>(std::move(f));
46 listeners.push_back(sp);
47 return sp;
48 }
49
50 // Unregister a listener
51 void unregisterListener(Token&& t) { t = nullptr; }
52
56 void notify(Args... args) {
57 trim();
58 for (auto& w : listeners) {
59 if (auto p = w.lock()) {
60 (*p)(args...);
61 }
62 }
63 }
64
65private:
66 // Remove expired listeners, we need that because the weak pointers could already be invalidated (i.e. refcount == 0).
67 void trim() {
68 listeners.erase(std::remove_if(listeners.begin(), listeners.end(), [](auto& p) { return p.expired(); }),
69 listeners.end());
70 }
71};
72
79template <typename... Signatures>
80class Broadcasters : public Broadcaster<Signatures>...
81{
82public:
83 using Broadcaster<Signatures>::registerListener...;
84 using Broadcaster<Signatures>::unregisterListener...;
85 using Broadcaster<Signatures>::notify...;
86
87 // Access a specific broadcaster for a given message type
88 template <typename M>
90 return *this;
91 }
92
93 // Access a specific broadcaster for a given message type (const version)
94 template <typename M>
95 const Broadcaster<M>& station() const {
96 return *this;
97 }
98};
99
100} // namespace Ikarus
Definition: assemblermanipulatorbuildingblocks.hh:22
Definition: broadcaster.hh:17
void unregisterListener(Token &&t)
Definition: broadcaster.hh:51
std::shared_ptr< F > Token
Definition: broadcaster.hh:33
void notify(Args... args)
This calls all the registered functions.
Definition: broadcaster.hh:56
Token registerListener(F f)
This method is used to register a Listener function.
Definition: broadcaster.hh:44
Fuses together multiple function signatures that can be emitted by one broadcaster....
Definition: broadcaster.hh:81
Broadcaster< M > & station()
Definition: broadcaster.hh:89
const Broadcaster< M > & station() const
Definition: broadcaster.hh:95