Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / include / xbt / signal.hpp
1 /* Copyright (c) 2014-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef SIMGRID_XBT_SIGNAL_HPP
7 #define SIMGRID_XBT_SIGNAL_HPP
8
9 #include <functional>
10 #include <map>
11 #include <utility>
12
13 namespace simgrid::xbt {
14
15 template <class S> class signal;
16
17 /** @brief
18  * A signal/slot mechanism, where you can attach callbacks to a given signal, and then fire the signal.
19  *
20  * The template parameter is the function signature of the signal (the return value currently ignored).
21  */
22 template <class R, class... P> class signal<R(P...)> {
23   using callback_type = std::function<R(P...)>;
24   std::map<unsigned int, callback_type> handlers_;
25   unsigned int callback_sequence_id = 0;
26
27 public:
28   /** Add a new callback to this signal */
29   template <class U> unsigned int connect(U slot)
30   {
31     handlers_.insert({callback_sequence_id, std::move(slot)});
32     return callback_sequence_id++;
33   }
34   /** Fire that signal, invoking all callbacks */
35   R operator()(P... args) const
36   {
37     for (auto const& [_, callback] : handlers_)
38       callback(args...);
39   }
40   /** Remove a callback */
41   void disconnect(unsigned int id) { handlers_.erase(id); }
42   /** Remove all callbacks */
43   void disconnect_slots() { handlers_.clear(); }
44 };
45 } // namespace simgrid::xbt
46
47 #endif