Skip to content

Commit e3014f1

Browse files
authored
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>
1 parent 2bb9d59 commit e3014f1

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

include/nlohmann/detail/conversions/from_json.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
5353
}
5454

5555
#ifdef JSON_HAS_CPP_17
56-
template<typename BasicJsonType, typename T>
56+
template < typename BasicJsonType, typename T,
57+
typename std::enable_if < !nlohmann::detail::is_basic_json<T>::value, int >::type = 0 >
5758
void from_json(const BasicJsonType& j, std::optional<T>& opt)
5859
{
5960
if (j.is_null())

single_include/nlohmann/json.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4889,7 +4889,8 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
48894889
}
48904890

48914891
#ifdef JSON_HAS_CPP_17
4892-
template<typename BasicJsonType, typename T>
4892+
template < typename BasicJsonType, typename T,
4893+
typename std::enable_if < !nlohmann::detail::is_basic_json<T>::value, int >::type = 0 >
48934894
void from_json(const BasicJsonType& j, std::optional<T>& opt)
48944895
{
48954896
if (j.is_null())

tests/src/unit-regression2.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,21 @@ TEST_CASE("regression tests 2")
11181118
const auto decoded = json_4804::from_cbor(data);
11191119
CHECK((decoded == json_4804::array()));
11201120
}
1121+
1122+
SECTION("issue #5046 - implicit conversion of return json to std::optional no longer implicit")
1123+
{
1124+
const json jval{};
1125+
auto GetValue = [](const json & valRoot) -> std::optional<json>
1126+
{
1127+
if (valRoot.contains("default"))
1128+
{
1129+
return valRoot.at("default");
1130+
}
1131+
return std::nullopt;
1132+
};
1133+
auto result = GetValue(jval);
1134+
CHECK(!result.has_value());
1135+
}
11211136
#endif
11221137
}
11231138

0 commit comments

Comments
 (0)