💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.1 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef ANTKEEPER_EVENT_HANDLER_HPP
  20. #define ANTKEEPER_EVENT_HANDLER_HPP
  21. #include "event.hpp"
  22. #include <type_traits>
  23. class event_dispatcher;
  24. /**
  25. * Abstract base class for event handlers.
  26. */
  27. class event_handler_base
  28. {
  29. private:
  30. friend class event_dispatcher;
  31. /**
  32. * Receives an event, casts it to its derived event type, then handles it.
  33. *
  34. * @param event Received event.
  35. */
  36. virtual void route_event(const event_base& event) = 0;
  37. };
  38. /**
  39. * Templates abstract base class for event handlers.
  40. *
  41. * @tparam Event type.
  42. */
  43. template <typename T>
  44. class event_handler: public event_handler_base
  45. {
  46. public:
  47. static_assert(std::is_base_of<event_base, T>::value, "T must be a descendant of event_base.");
  48. /// Returns the unique event type identifier for the event type handled by this event handler.
  49. const std::size_t get_handled_event_type_id() const;
  50. /**
  51. * Handles an event of type T.
  52. *
  53. * @param event Event to handle.
  54. */
  55. virtual void handle_event(const T& event) = 0;
  56. private:
  57. /// @copydoc event_handler_base::route_event()
  58. virtual void route_event(const event_base& event) final;
  59. };
  60. template <typename T>
  61. inline const std::size_t event_handler<T>::get_handled_event_type_id() const
  62. {
  63. return T::event_type_id;
  64. }
  65. template <typename T>
  66. void event_handler<T>::route_event(const event_base& event)
  67. {
  68. handle_event(static_cast<const T&>(event));
  69. }
  70. #endif // ANTKEEPER_EVENT_HANDLER_HPP