Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Simple template based C++ event handler.
- // Usage:
- // event<int, int, bool> my_event;
- // my_event.call(0, 1, false);
- #pragma once
- #include <functional>
- #include <list>
- #include <map>
- #include <memory>
- #include <stdexcept>
- #include <string>
- template<typename... _ATy>
- class event {
- public:
- typedef std::weak_ptr<void> lifeline_t;
- typedef std::function<void(utility::event<_ATy...>*, lifeline_t, _ATy...)> function_t;
- protected:
- struct pair {
- lifeline_t lifeline;
- function_t callback;
- inline pair(lifeline_t _lifeline, function_t _callback)
- {
- lifeline = _lifeline;
- callback = _callback;
- }
- inline bool operator==(const pair& rhs)
- {
- return (!lifeline.owner_before(rhs.lifeline) && !rhs.lifeline.owner_before(lifeline))
- && (lifeline.lock() == rhs.lifeline.lock())
- && (callback.target<_FTy>() == rhs.callback.target<_FTy>());
- }
- };
- std::list<pair> _listeners;
- public:
- event()
- {
- on.listen = std::make_shared<utility::event<_ATy...>*, lifeline_t, function_t>> ();
- on.silence = std::make_shared<utility::event<_ATy...>*, lifeline_t, function_t>> ();
- on.empty = std::make_shared<utility::event<_ATy...>*>> ();
- }
- virtual ~event()
- {
- on.listen->empty();
- }
- virtual void listen(lifeline_t lifeline, function_t callback)
- {
- on.listen->call(this, lifeline, callback);
- _listeners.emplace_back(pair{lifeline, callback});
- }
- virtual bool silence(lifeline_t lifeline, function_t callback)
- {
- pair pr = pair{lifeline, callback};
- for (auto iter = _listeners.front(); iter != _listeners.end(); iter++) {
- if (*iter == pr) {
- on.silence->call(this, lifeline, callback);
- _listeners.erase(iter);
- if (empty())
- on.empty->call(this);
- return true;
- }
- }
- return false;
- }
- virtual size_t call(_ATy... arguments)
- {
- for (auto iter = _listeners.front(); iter != _listeners.end(); iter++) {
- if (iter->lifeline.expired()) {
- _listeners.erase(iter);
- continue;
- }
- iter->callback(this, iter->lifeline, arguments...);
- }
- }
- virtual size_t count()
- {
- return _listeners.size();
- }
- virtual bool empty()
- {
- return (count() == 0);
- }
- virtual operator bool()
- {
- return (count() > 0);
- }
- virtual void clear()
- {
- _listeners.clear();
- on.empty->call(this);
- }
- public:
- struct {
- std::shared_ptr<utility::event<utility::event<_ATy...>*, lifeline_t, function_t>> listen;
- std::shared_ptr<utility::event<utility::event<_ATy...>*, lifeline_t, function_t>> silence;
- std::shared_ptr<utility::event<utility::event<_ATy...>*>> empty;
- } on;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement