aboutsummaryrefslogtreecommitdiff
path: root/include/cru/common
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2019-03-31 19:48:20 +0800
committercrupest <crupest@outlook.com>2019-03-31 19:48:20 +0800
commit8ca0873597eb05a2f120d3ea107660abcff4533c (patch)
treef2089ad1a420ae0f21ba0d84b5031de3b5e489ca /include/cru/common
parent9cc0f5d9192288116443254d790aa9ab36572b8d (diff)
downloadcru-8ca0873597eb05a2f120d3ea107660abcff4533c.tar.gz
cru-8ca0873597eb05a2f120d3ea107660abcff4533c.tar.bz2
cru-8ca0873597eb05a2f120d3ea107660abcff4533c.zip
...
Diffstat (limited to 'include/cru/common')
-rw-r--r--include/cru/common/event.hpp46
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