mirror of
https://github.com/nlohmann/json.git
synced 2026-03-08 02:01:24 +00:00
🚧 conversions for std::optional
This commit is contained in:
@@ -13,6 +13,10 @@
|
||||
#include <utility> // pair, declval
|
||||
#include <valarray> // valarray
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <optional> // optional
|
||||
#endif
|
||||
|
||||
#include <nlohmann/detail/exceptions.hpp>
|
||||
#include <nlohmann/detail/macro_scope.hpp>
|
||||
#include <nlohmann/detail/meta/cpp_future.hpp>
|
||||
@@ -33,6 +37,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
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
#include <valarray> // valarray
|
||||
#include <vector> // vector
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <optional> // optional
|
||||
#endif
|
||||
|
||||
#include <nlohmann/detail/iterators/iteration_proxy.hpp>
|
||||
#include <nlohmann/detail/meta/cpp_future.hpp>
|
||||
#include <nlohmann/detail/meta/type_traits.hpp>
|
||||
@@ -198,6 +202,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