context.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // context.h
  3. // reflection
  4. //
  5. // Created by Sam Jaffe on 8/6/22.
  6. // Copyright © 2022 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <initializer_list>
  10. #include <utility>
  11. #include "reflection/forward.h"
  12. #include "reflection/object.h"
  13. namespace reflection {
  14. class Context {
  15. public:
  16. struct Arg : std::pair<std::string_view, Object> {
  17. template <typename T> Arg(std::string_view id, T &&value)
  18. : pair(id, Object(std::forward<T>(value), std::string(id))) {}
  19. Arg(Object &&obj) : pair("", std::move(obj)) { first = second.name(); }
  20. };
  21. public:
  22. explicit Context(std::initializer_list<Arg> data) : data_(data.begin(), data.end()) {}
  23. Object const & get(std::string_view id) const { return data_.at(id); }
  24. bool has(std::string_view id) const { return data_.count(id); }
  25. template <typename C,
  26. typename = std::enable_if_t<std::is_constructible_v<
  27. std::string_view, decltype(*std::begin(std::declval<C>()))>>>
  28. Object get(C const & container) const {
  29. return Object::get(get(*std::begin(container)), ++std::begin(container),
  30. std::end(container));
  31. }
  32. private:
  33. std::unordered_map<std::string_view, Object> data_;
  34. };
  35. }