Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'models_type_rework_part2_try2' into 'master'
[simgrid.git] / include / xbt / signal.hpp
1 /* Copyright (c) 2014-2021. 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 {
14 namespace xbt {
15
16 template <class S> class signal;
17
18 /** @brief
19  * A signal/slot mechanism, where you can attach callbacks to a given signal, and then fire the signal.
20  *
21  * The template parameter is the function signature of the signal (the return value currently ignored).
22  */
23 template <class R, class... P> class signal<R(P...)> {
24   using callback_type = std::function<R(P...)>;
25   std::map<unsigned int, callback_type> handlers_;
26   unsigned int callback_sequence_id = 0;
27
28 public:
29   /** Add a new callback to this signal */
30   template <class U> unsigned int connect(U slot)
31   {
32     handlers_.insert({callback_sequence_id, std::move(slot)});
33     return callback_sequence_id++;
34   }
35   /** Fire that signal, invoking all callbacks */
36   R operator()(P... args) const
37   {
38     for (auto const& handler : handlers_)
39       handler.second(args...);
40   }
41   /** Remove a callback */
42   void disconnect(unsigned int id) { handlers_.erase(id); }
43   /** Remove all callbacks */
44   void disconnect_slots() { handlers_.clear(); }
45   /** Get the amount of callbacks */
46   int get_slot_count() { return handlers_.size(); }
47 };
48 }
49 }
50
51 #endif