diff options
author | crupest <crupest@outlook.com> | 2019-03-31 19:48:20 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2019-03-31 19:48:20 +0800 |
commit | 8ca0873597eb05a2f120d3ea107660abcff4533c (patch) | |
tree | f2089ad1a420ae0f21ba0d84b5031de3b5e489ca /include/cru/common/event.hpp | |
parent | 9cc0f5d9192288116443254d790aa9ab36572b8d (diff) | |
download | cru-8ca0873597eb05a2f120d3ea107660abcff4533c.tar.gz cru-8ca0873597eb05a2f120d3ea107660abcff4533c.tar.bz2 cru-8ca0873597eb05a2f120d3ea107660abcff4533c.zip |
...
Diffstat (limited to 'include/cru/common/event.hpp')
-rw-r--r-- | include/cru/common/event.hpp | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/include/cru/common/event.hpp b/include/cru/common/event.hpp new file mode 100644 index 00000000..ce014fb8 --- /dev/null +++ b/include/cru/common/event.hpp @@ -0,0 +1,46 @@ +#pragma once +#include "base.hpp" + +#include <functional> +#include <map> +#include <utility> + +namespace cru { +// A non-copyable non-movable Event class. +// It stores a list of event handlers. +template <typename... TArgs> +class Event { + public: + using EventHandler = std::function<void(TArgs...)>; + using EventHandlerToken = long; + + Event() = default; + Event(const Event&) = delete; + Event& operator=(const Event&) = delete; + Event(Event&&) = delete; + Event& operator=(Event&&) = delete; + ~Event() = default; + + EventHandlerToken AddHandler(const EventHandler& handler) { + const auto token = current_token_++; + handlers_.emplace(token, handler); + return token; + } + + void RemoveHandler(const EventHandlerToken token) { + auto find_result = handlers_.find(token); + if (find_result != handlers_.cend()) handlers_.erase(find_result); + } + + template <typename... Args> + void Raise(Args&&... args) { + for (const auto& handler : handlers_) + (handler.second)(std::forward<Args>(args)...); + } + + private: + std::map<EventHandlerToken, EventHandler> handlers_; + + EventHandlerToken current_token_ = 0; +}; +} // namespace cru |