Fix conversion to std::optional (#5052)

* 🐛 fix conversion to std::optional

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* 🚨 fix warning

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* 🚨 fix warning

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Niels Lohmann
2026-01-13 17:19:34 +01:00
committed by GitHub
parent 2bb9d59fde
commit e3014f162a
3 changed files with 19 additions and 2 deletions

View File

@@ -53,7 +53,8 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
}
#ifdef JSON_HAS_CPP_17
template<typename BasicJsonType, typename T>
template < typename BasicJsonType, typename T,
typename std::enable_if < !nlohmann::detail::is_basic_json<T>::value, int >::type = 0 >
void from_json(const BasicJsonType& j, std::optional<T>& opt)
{
if (j.is_null())

View File

@@ -4889,7 +4889,8 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
}
#ifdef JSON_HAS_CPP_17
template<typename BasicJsonType, typename T>
template < typename BasicJsonType, typename T,
typename std::enable_if < !nlohmann::detail::is_basic_json<T>::value, int >::type = 0 >
void from_json(const BasicJsonType& j, std::optional<T>& opt)
{
if (j.is_null())

View File

@@ -1118,6 +1118,21 @@ TEST_CASE("regression tests 2")
const auto decoded = json_4804::from_cbor(data);
CHECK((decoded == json_4804::array()));
}
SECTION("issue #5046 - implicit conversion of return json to std::optional no longer implicit")
{
const json jval{};
auto GetValue = [](const json & valRoot) -> std::optional<json>
{
if (valRoot.contains("default"))
{
return valRoot.at("default");
}
return std::nullopt;
};
auto result = GetValue(jval);
CHECK(!result.has_value());
}
#endif
}