mirror of
https://github.com/nlohmann/json.git
synced 2026-03-19 23:45:59 +00:00
🚧 conversions for std::optional
This commit is contained in:
@@ -69,6 +69,10 @@ SOFTWARE.
|
||||
#include <utility> // pair, declval
|
||||
#include <valarray> // valarray
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <optional> // optional
|
||||
#endif
|
||||
|
||||
// #include <nlohmann/detail/exceptions.hpp>
|
||||
|
||||
|
||||
@@ -2904,6 +2908,21 @@ void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
|
||||
n = nullptr;
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
template<typename BasicJsonType, typename T>
|
||||
void from_json(const BasicJsonType& j, std::optional<T>& opt)
|
||||
{
|
||||
if (j.is_null())
|
||||
{
|
||||
opt = std::nullopt;
|
||||
}
|
||||
else
|
||||
{
|
||||
opt = j.template get<T>();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// overloads for basic_json template parameters
|
||||
template<typename BasicJsonType, typename ArithmeticType,
|
||||
enable_if_t<std::is_arithmetic<ArithmeticType>::value and
|
||||
@@ -3272,6 +3291,10 @@ constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::va
|
||||
#include <valarray> // valarray
|
||||
#include <vector> // vector
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <optional> // optional
|
||||
#endif
|
||||
|
||||
// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
|
||||
|
||||
|
||||
@@ -3642,6 +3665,22 @@ struct external_constructor<value_t::object>
|
||||
// to_json //
|
||||
/////////////
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
template<typename BasicJsonType, typename T,
|
||||
enable_if_t<std::is_constructible<BasicJsonType, T>::value, int> = 0>
|
||||
void to_json(BasicJsonType& j, const std::optional<T>& opt)
|
||||
{
|
||||
if (opt.has_value())
|
||||
{
|
||||
j = *opt;
|
||||
}
|
||||
else
|
||||
{
|
||||
j = nullptr;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
template<typename BasicJsonType, typename T,
|
||||
enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
|
||||
void to_json(BasicJsonType& j, T b) noexcept
|
||||
|
||||
Reference in New Issue
Block a user