X-Git-Url: http://info.iut-bm.univ-fcomte.fr/pub/gitweb/simgrid.git/blobdiff_plain/dccf1b41e9c7b5a696f01abceaa2779fe65f154f..e71a2a302d28430dc1bfee906f842f5f3d0fa3ce:/include/xbt/signal.hpp diff --git a/include/xbt/signal.hpp b/include/xbt/signal.hpp index 508822cf2b..ef4ec9cf35 100644 --- a/include/xbt/signal.hpp +++ b/include/xbt/signal.hpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2014-2015. The SimGrid Team. All rights reserved. */ +/* Copyright (c) 2014-2021. The SimGrid Team. All rights reserved. */ /* This program is free software; you can redistribute it and/or modify it * under the terms of the license (GNU LGPL) which comes with this package. */ @@ -7,42 +7,44 @@ #define SIMGRID_XBT_SIGNAL_HPP #include +#include #include -#include namespace simgrid { namespace xbt { - template class signal; - - /** A signal/slot mechanism - * - * S is expected to be the function signature of the signal. - * I'm not sure we need a return value (it is currently ignored). - * If we don't we might use `signal` instead. - */ - template - class signal { - private: - typedef std::function callback_type; - std::vector handlers_; - public: - template - void connect(U slot) - { - handlers_.push_back(std::move(slot)); - } - R operator()(P... args) const - { - for (auto& handler : handlers_) - handler(args...); - } - void disconnect_all_slots() - { - handlers_.clear(); - } - }; - +template class signal; + +/** @brief + * A signal/slot mechanism, where you can attach callbacks to a given signal, and then fire the signal. + * + * The template parameter is the function signature of the signal (the return value currently ignored). + */ +template class signal { + using callback_type = std::function; + std::map handlers_; + unsigned int callback_sequence_id = 0; + +public: + /** Add a new callback to this signal */ + template unsigned int connect(U slot) + { + handlers_.insert({callback_sequence_id, std::move(slot)}); + return callback_sequence_id++; + } + /** Fire that signal, invoking all callbacks */ + R operator()(P... args) const + { + for (auto const& handler : handlers_) + handler.second(args...); + } + /** Remove a callback */ + void disconnect(unsigned int id) { handlers_.erase(id); } + /** Remove all callbacks */ + void disconnect_slots() { handlers_.clear(); } + /** Get the amount of callbacks */ + int get_slot_count() { return handlers_.size(); } +}; } }