1 /* Copyright (c) 2014-2021. The SimGrid Team. All rights reserved. */
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. */
6 #ifndef SIMGRID_XBT_SIGNAL_HPP
7 #define SIMGRID_XBT_SIGNAL_HPP
16 template<class S> class signal;
18 /** A signal/slot mechanism
20 * The template parameter is the function signature of the signal.
21 * The return value currently ignored.
23 template<class R, class... P>
24 class signal<R(P...)> {
25 using callback_type = std::function<R(P...)>;
26 std::map<unsigned int, callback_type> handlers_;
27 unsigned int callback_sequence_id = 0;
30 /** Add a new callback to this signal */
31 template <class U> unsigned int connect(U slot)
33 handlers_.insert({callback_sequence_id, std::move(slot)});
34 return callback_sequence_id++;
36 /** Fire that signal, invoking all callbacks */
37 R operator()(P... args) const
39 for (auto const& handler : handlers_)
40 handler.second(args...);
42 /** Remove a callback */
43 void disconnect(unsigned int id) { handlers_.erase(id); }
44 /** Remove all callbacks */
45 void disconnect_slots() { handlers_.clear(); }
46 /** Get the amount of callbacks */
47 int get_slot_count() { return handlers_.size(); }