forward.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // forward.h
  3. // reflection
  4. //
  5. // Created by Sam Jaffe on 7/3/22.
  6. // Copyright © 2022 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <functional>
  10. #include <map>
  11. #include <string>
  12. #include <type_traits>
  13. #include <typeindex>
  14. #include <unordered_map>
  15. namespace reflection {
  16. class Context;
  17. class Object;
  18. class Property;
  19. template <typename Obj, typename = void> class Reflection;
  20. template <typename T> class Proxy;
  21. template <typename T> class TypeCast;
  22. template <typename Func> using Cache = std::map<std::string_view, Func>;
  23. template <typename T> using TypeMap = std::unordered_map<std::type_index, T>;
  24. template <typename Obj>
  25. using Accessor = std::function<Object(Obj &, std::string)>;
  26. template <typename Obj>
  27. using Getter = std::function<Object(Obj const &, std::string)>;
  28. template <typename T> constexpr std::string_view Name = "";
  29. }
  30. #define reflect(object) reflection::Object(object, #object)
  31. #define INSTANTIATE_REFLECTION_IMPL(T, name, ...) \
  32. template <> constexpr std::string_view Name<T> = name; \
  33. template Cache<Accessor<T>> Reflection<T>::members_; \
  34. template Cache<Getter<T>> Reflection<T>::const_members_
  35. #define INSTANTIATE_REFLECTION(T, ...) \
  36. INSTANTIATE_REFLECTION_IMPL(T, ##__VA_ARGS__, #T)
  37. #define INSTANTIATE_REFLECTION_TYPECAST_IMPL(T, name, ...) \
  38. template <> constexpr std::string_view Name<T> = name; \
  39. template TypeMap<std::function<T(Object const &)>> TypeCast<T>::get_; \
  40. template TypeMap<std::function<void(Object &, T const &)>> TypeCast<T>::set_
  41. #define INSTANTIATE_REFLECTION_TYPECAST(T, ...) \
  42. INSTANTIATE_REFLECTION_TYPECAST_IMPL(T, ##__VA_ARGS__, #T)
  43. #if !defined(CONCAT)
  44. #define CONCAT_IMPL(A, B) A##B
  45. #define CONCAT(A, B) CONCAT_IMPL(A, B)
  46. #endif
  47. #define REFLECTION(T) \
  48. bool const CONCAT(reflection_, __LINE__) = ::reflection::Reflection<T>()
  49. #define REFLECTION_TYPE_CAST(T) \
  50. bool const CONCAT(type_cast_, __LINE__) = ::reflection::TypeCast<T>()
  51. #define IS_SCOPE_CONTAINER(C) \
  52. std::is_constructible_v<std::string_view, \
  53. decltype(*std::begin(std::declval<C>()))>