Skip to content

Commit

Permalink
Only define conversion to std::optional when JSON_USE_IMPLICIT_CONVER…
Browse files Browse the repository at this point in the history
…SION is disabled.
  • Loading branch information
fsandhei committed Mar 21, 2024
1 parent d27adfd commit 1a8d427
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
5 changes: 4 additions & 1 deletion include/nlohmann/detail/conversions/from_json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
}

#ifdef JSON_HAS_CPP_17
#ifndef JSON_USE_IMPLICIT_CONVERSIONS
template<typename BasicJsonType, typename T>
void from_json(const BasicJsonType& j, std::optional<T>& opt)
{
Expand All @@ -56,7 +57,9 @@ void from_json(const BasicJsonType& j, std::optional<T>& opt)
opt.emplace(j.template get<T>());
}
}
#endif

#endif // JSON_USE_IMPLICIT_CONVERSIONS
#endif // JSON_HAS_CPP_17

// overloads for basic_json template parameters
template < typename BasicJsonType, typename ArithmeticType,
Expand Down
5 changes: 4 additions & 1 deletion single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4616,6 +4616,7 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
}

#ifdef JSON_HAS_CPP_17
#ifndef JSON_USE_IMPLICIT_CONVERSIONS
template<typename BasicJsonType, typename T>
void from_json(const BasicJsonType& j, std::optional<T>& opt)
{
Expand All @@ -4628,7 +4629,9 @@ void from_json(const BasicJsonType& j, std::optional<T>& opt)
opt.emplace(j.template get<T>());
}
}
#endif

#endif // JSON_USE_IMPLICIT_CONVERSIONS
#endif // JSON_HAS_CPP_17

// overloads for basic_json template parameters
template < typename BasicJsonType, typename ArithmeticType,
Expand Down
6 changes: 4 additions & 2 deletions tests/src/unit-conversions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,7 @@ TEST_CASE("JSON to enum mapping")
}

#ifdef JSON_HAS_CPP_17
#ifndef JSON_USE_IMPLICIT_CONVERSIONS
TEST_CASE("std::optional")
{
SECTION("null")
Expand Down Expand Up @@ -1605,7 +1606,7 @@ TEST_CASE("std::optional")
std::optional<int> opt_int = 1;

CHECK(json(opt_int) == j_number);
CHECK(std::optional<int>(j_number) == opt_int);
CHECK(j_number.get<std::optional<int>>() == opt_int);
}

SECTION("array")
Expand All @@ -1614,7 +1615,7 @@ TEST_CASE("std::optional")
std::vector<std::optional<int>> opt_array = {{1, 2, std::nullopt}};

CHECK(json(opt_array) == j_array);
CHECK(std::vector<std::optional<int>>(j_array) == opt_array);
CHECK(j_array.get<std::vector<std::optional<int>>>() == opt_array);
}

SECTION("object")
Expand All @@ -1627,6 +1628,7 @@ TEST_CASE("std::optional")
}
}
#endif
#endif

#ifdef JSON_HAS_CPP_17
#undef JSON_HAS_CPP_17
Expand Down

0 comments on commit 1a8d427

Please sign in to comment.