From b4eece01f873a752367a37339078836d5ef05566 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Fri, 9 Feb 2018 09:05:29 +0100 Subject: [PATCH] Fixed `JsonVariant::operator|(int)` to accept double (fixes #675) --- CHANGELOG.md | 5 +++++ src/ArduinoJson/JsonVariantOr.hpp | 20 +++++++++++++++++--- test/JsonVariant/or.cpp | 6 ++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3646765e..276beb93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ ArduinoJson: change log ======================= +HEAD +---- + +* Fixed `JsonVariant::operator|(int)` that returned the default value if the variant contained a double (issue #675) + v5.13.0 ------- diff --git a/src/ArduinoJson/JsonVariantOr.hpp b/src/ArduinoJson/JsonVariantOr.hpp index cad5626a..d8022fcb 100644 --- a/src/ArduinoJson/JsonVariantOr.hpp +++ b/src/ArduinoJson/JsonVariantOr.hpp @@ -6,6 +6,8 @@ #include "Data/JsonVariantAs.hpp" #include "Polyfills/attributes.hpp" +#include "TypeTraits/EnableIf.hpp" +#include "TypeTraits/IsIntegral.hpp" namespace ArduinoJson { namespace Internals { @@ -15,7 +17,8 @@ class JsonVariantOr { public: // Returns the default value if the JsonVariant is undefined of incompatible template - T operator|(const T &defaultValue) const { + typename EnableIf::value, T>::type operator|( + const T &defaultValue) const { if (impl()->template is()) return impl()->template as(); else @@ -29,10 +32,21 @@ class JsonVariantOr { return value ? value : defaultValue; } + // Returns the default value if the JsonVariant is undefined of incompatible + // Special case for integers: we also accept double + template + typename EnableIf::value, Integer>::type operator|( + const Integer &defaultValue) const { + if (impl()->template is()) + return impl()->template as(); + else + return defaultValue; + } + private: const TImpl *impl() const { return static_cast(this); } }; -} -} +} // namespace Internals +} // namespace ArduinoJson diff --git a/test/JsonVariant/or.cpp b/test/JsonVariant/or.cpp index 51687dea..84349463 100644 --- a/test/JsonVariant/or.cpp +++ b/test/JsonVariant/or.cpp @@ -51,6 +51,12 @@ TEST_CASE("JsonVariant::operator|()") { REQUIRE(result == 0); } + SECTION("double | int") { + JsonVariant variant = 42.0; + int result = variant | 666; + REQUIRE(result == 42); + } + SECTION("bool | bool") { JsonVariant variant = false; bool result = variant | true;