json_ref.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include <initializer_list>
  3. #include <utility>
  4. #include <nlohmann/detail/meta/type_traits.hpp>
  5. namespace nlohmann
  6. {
  7. namespace detail
  8. {
  9. template<typename BasicJsonType>
  10. class json_ref
  11. {
  12. public:
  13. using value_type = BasicJsonType;
  14. json_ref(value_type&& value)
  15. : owned_value(std::move(value))
  16. {}
  17. json_ref(const value_type& value)
  18. : value_ref(&value)
  19. {}
  20. json_ref(std::initializer_list<json_ref> init)
  21. : owned_value(init)
  22. {}
  23. template <
  24. class... Args,
  25. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  26. json_ref(Args && ... args)
  27. : owned_value(std::forward<Args>(args)...)
  28. {}
  29. // class should be movable only
  30. json_ref(json_ref&&) noexcept = default;
  31. json_ref(const json_ref&) = delete;
  32. json_ref& operator=(const json_ref&) = delete;
  33. json_ref& operator=(json_ref&&) = delete;
  34. ~json_ref() = default;
  35. value_type moved_or_copied() const
  36. {
  37. if (value_ref == nullptr)
  38. {
  39. return std::move(owned_value);
  40. }
  41. return *value_ref;
  42. }
  43. value_type const& operator*() const
  44. {
  45. return value_ref ? *value_ref : owned_value;
  46. }
  47. value_type const* operator->() const
  48. {
  49. return &** this;
  50. }
  51. private:
  52. mutable value_type owned_value = nullptr;
  53. value_type const* value_ref = nullptr;
  54. };
  55. } // namespace detail
  56. } // namespace nlohmann