1
0
mirror of https://github.com/nlohmann/json.git synced 2025-07-31 10:24:23 +03:00

Fix conversion to std::optional (#4742)

* ⚗️ remove JSON_USE_IMPLICIT_CONVERSIONS check for from_json(json, std::optional)

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

* ⚗️ remove JSON_USE_IMPLICIT_CONVERSIONS check for from_json(json, std::optional)

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

* ⚗️ remove JSON_USE_IMPLICIT_CONVERSIONS check for from_json(json, std::optional)

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

* ⚗️ remove JSON_USE_IMPLICIT_CONVERSIONS check for from_json(json, std::optional)

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

* ⚗️ remove JSON_USE_IMPLICIT_CONVERSIONS check for from_json(json, std::optional)

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

* ⚗️ add C++ standard library as matrix option

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

*  remove inline

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

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Niels Lohmann
2025-04-15 16:10:39 +02:00
committed by GitHub
parent 4cca3b9cb2
commit 96c1b52f1c
4 changed files with 55 additions and 14 deletions

View File

@ -36,6 +36,14 @@ using ordered_json = nlohmann::ordered_json;
#include <variant>
#endif
#ifdef JSON_HAS_CPP_17
#if __has_include(<optional>)
#include <optional>
#elif __has_include(<experimental/optional>)
#include <experimental/optional>
#endif
#endif
#ifdef JSON_HAS_CPP_20
#if __has_include(<span>)
#include <span>
@ -390,6 +398,19 @@ struct Example_3810
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Example_3810, bla); // NOLINT(misc-use-internal-linkage)
/////////////////////////////////////////////////////////////////////
// for #4740
/////////////////////////////////////////////////////////////////////
#ifdef JSON_HAS_CPP_17
struct Example_4740
{
std::optional<std::string> host = std::nullopt;
std::optional<int> port = std::nullopt;
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Example_4740, host, port)
};
#endif
TEST_CASE("regression tests 2")
{
SECTION("issue #1001 - Fix memory leak during parser callback")
@ -1037,6 +1058,28 @@ TEST_CASE("regression tests 2")
oj["test"] = states;
CHECK(oj["test"].dump() == expected);
}
#ifdef JSON_HAS_CPP_17
SECTION("issue #4740 - build issue with std::optional")
{
const auto t1 = Example_4740();
const auto j1 = nlohmann::json(t1);
CHECK(j1.dump() == "{\"host\":null,\"port\":null}");
const auto t2 = j1.get<Example_4740>();
CHECK(!t2.host.has_value());
CHECK(!t2.port.has_value());
// improve coverage
auto t3 = Example_4740();
t3.port = 80;
t3.host = "example.com";
const auto j2 = nlohmann::json(t3);
CHECK(j2.dump() == "{\"host\":\"example.com\",\"port\":80}");
const auto t4 = j2.get<Example_4740>();
CHECK(t4.host.has_value());
CHECK(t4.port.has_value());
}
#endif
}
DOCTEST_CLANG_SUPPRESS_WARNING_POP