Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
deprecate xbt_mutex and xbt_cond
[simgrid.git] / include / xbt / signal.hpp
1 /* Copyright (c) 2014-2019. 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   /** A signal/slot mechanism
19   *
20   *  S is expected to be the function signature of the signal.
21   *  I'm not sure we need a return value (it is currently ignored).
22   *  If we don't we might use `signal<P1, P2, ...>` instead.
23   */
24   template<class R, class... P>
25   class signal<R(P...)> {
26     typedef std::function<R(P...)> callback_type;
27     std::map<unsigned int, callback_type> handlers_;
28     unsigned int callback_sequence_id = 0;
29
30   public:
31     template <class U> unsigned int connect(U slot)
32     {
33       handlers_.insert({callback_sequence_id, std::move(slot)});
34       return callback_sequence_id++;
35     }
36     R operator()(P... args) const
37     {
38       for (auto const& handler : handlers_)
39         handler.second(args...);
40     }
41     void disconnect(unsigned int id) { handlers_.erase(id); }
42     void disconnect_slots() { handlers_.clear(); }
43     int get_slot_count() { return handlers_.size(); }
44   };
45
46 }
47 }
48
49 #endif