From 48ee4a178b4f8e4ec23944362dd1f4899ee36b72 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Sat, 21 Sep 2024 09:22:12 +0200 Subject: [PATCH] Use a `const` reference in `is_convertible()` --- extras/tests/Misc/CMakeLists.txt | 1 + extras/tests/Misc/issue2129.cpp | 55 +++++++++++++++++++ .../Polyfills/type_traits/is_convertible.hpp | 2 +- 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 extras/tests/Misc/issue2129.cpp diff --git a/extras/tests/Misc/CMakeLists.txt b/extras/tests/Misc/CMakeLists.txt index 82f1a0c67..4230a9cf6 100644 --- a/extras/tests/Misc/CMakeLists.txt +++ b/extras/tests/Misc/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(MiscTests arithmeticCompare.cpp conflicts.cpp issue1967.cpp + issue2129.cpp JsonString.cpp NoArduinoHeader.cpp printable.cpp diff --git a/extras/tests/Misc/issue2129.cpp b/extras/tests/Misc/issue2129.cpp new file mode 100644 index 000000000..8b336f2cf --- /dev/null +++ b/extras/tests/Misc/issue2129.cpp @@ -0,0 +1,55 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2024, Benoit BLANCHON +// MIT License + +#include +#include + +template +class Nullable { + public: + Nullable() : value_{} {} + Nullable(T value) : value_{value} {} + + operator T() const { + return value_; + } + + operator T&() { + return value_; + } + + bool is_valid() const { + return value_ != invalid_value_; + } + + T value() const { + return value_; + } + + private: + T value_; + static T invalid_value_; +}; + +template <> +float Nullable::invalid_value_ = std::numeric_limits::lowest(); + +template +void convertToJson(const Nullable& src, JsonVariant dst) { + if (src.is_valid()) { + dst.set(src.value()); + } else { + dst.clear(); + } +} + +TEST_CASE("Issue #2129") { + Nullable nullable_value = Nullable{123.4f}; + + JsonDocument doc; + + doc["value"] = nullable_value; + + REQUIRE(doc["value"].as() == Approx(123.4f)); +} diff --git a/src/ArduinoJson/Polyfills/type_traits/is_convertible.hpp b/src/ArduinoJson/Polyfills/type_traits/is_convertible.hpp index c6919d48f..e906ab77b 100644 --- a/src/ArduinoJson/Polyfills/type_traits/is_convertible.hpp +++ b/src/ArduinoJson/Polyfills/type_traits/is_convertible.hpp @@ -27,7 +27,7 @@ struct is_convertible { static int probe(To); static char probe(...); - static From& from_; + static const From& from_; public: static const bool value = sizeof(probe(from_)) == sizeof(int);