eliasdaler

Untitled

Nov 29th, 2015
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. using hash_type = std::uint64_t;
  2. constexpr auto fnv_basis = 14695981039346656037ull;
  3. constexpr auto fnv_prime = 109951162821ull;
  4.  
  5. constexpr hash_type hash(const char *str, hash_type h = fnv_basis)
  6. {
  7.     return *str ? hash(str + 1, (h ^ *str) * fnv_prime) : h;
  8. }
  9.  
  10. // all unregistered event types will call this function
  11. template <hash_type Hash>
  12. constexpr int checkRegistered()
  13. {
  14.     static_assert(false, "Event type is not registered");
  15.     return 0; // because we can't do constexpr void
  16. }
  17.  
  18. // "registration" is done by template specialization
  19. #define REGISTER_EVENT_TYPE(type)           \
  20. template <>                                 \
  21. constexpr int checkRegistered<hash(type)>() \
  22. {                                           \
  23.     return 0;                               \
  24. }                                           \
  25.  
  26. REGISTER_EVENT_TYPE("LevelChangedEvent")
  27.  
  28. template <hash_type EventType>
  29. void doStuff()
  30. {
  31.     checkRegistered<EventType>(); // compile time check if type is registered!
  32.     ... // do stuff
  33. }
  34.  
  35. int main()
  36. {
  37.     doStuff<hash("LevelChangedEvent")>(); // ok
  38.     doStuff<hash("HpChangedEvent")>(); // static_assert expected here
  39. }
Advertisement
Add Comment
Please, Sign In to add comment