json/include/nlohmann/detail/json_ref.hpp

77 lines
1.7 KiB
C++
Raw Normal View History

2018-01-10 17:18:31 +08:00
#pragma once
2017-08-15 00:14:27 +08:00
#include <initializer_list>
#include <utility>
#include <nlohmann/detail/meta/type_traits.hpp>
2017-08-15 00:14:27 +08:00
namespace nlohmann
{
namespace detail
{
template<typename BasicJsonType>
class json_ref
{
public:
using value_type = BasicJsonType;
json_ref(value_type&& value)
2020-06-23 04:32:21 +08:00
: owned_value(std::move(value))
, value_ref(&owned_value)
, is_rvalue(true)
2017-08-15 00:14:27 +08:00
{}
json_ref(const value_type& value)
2020-06-23 04:32:21 +08:00
: value_ref(const_cast<value_type*>(&value))
, is_rvalue(false)
2017-08-15 00:14:27 +08:00
{}
json_ref(std::initializer_list<json_ref> init)
2020-06-23 04:32:21 +08:00
: owned_value(init)
, value_ref(&owned_value)
, is_rvalue(true)
2017-08-15 00:14:27 +08:00
{}
template <
class... Args,
enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
json_ref(Args && ... args)
2020-06-23 04:32:21 +08:00
: owned_value(std::forward<Args>(args)...)
, value_ref(&owned_value)
, is_rvalue(true)
{}
2017-08-15 00:14:27 +08:00
// class should be movable only
2019-03-17 22:20:22 +08:00
json_ref(json_ref&&) = default;
2017-08-15 00:14:27 +08:00
json_ref(const json_ref&) = delete;
json_ref& operator=(const json_ref&) = delete;
2018-10-08 12:54:51 +08:00
json_ref& operator=(json_ref&&) = delete;
~json_ref() = default;
2017-08-15 00:14:27 +08:00
value_type moved_or_copied() const
{
if (is_rvalue)
{
return std::move(*value_ref);
}
return *value_ref;
}
value_type const& operator*() const
{
return *static_cast<value_type const*>(value_ref);
}
value_type const* operator->() const
{
return static_cast<value_type const*>(value_ref);
}
private:
mutable value_type owned_value = nullptr;
value_type* value_ref = nullptr;
2020-06-23 04:32:21 +08:00
const bool is_rvalue = true;
2017-08-15 00:14:27 +08:00
};
} // namespace detail
} // namespace nlohmann