Fixed JsonVariant::operator|(int) to accept double (fixes #675)

This commit is contained in:
Benoit Blanchon
2018-02-09 09:05:29 +01:00
parent cf5396aaed
commit b4eece01f8
3 changed files with 28 additions and 3 deletions

View File

@ -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
-------

View File

@ -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 <typename T>
T operator|(const T &defaultValue) const {
typename EnableIf<!IsIntegral<T>::value, T>::type operator|(
const T &defaultValue) const {
if (impl()->template is<T>())
return impl()->template as<T>();
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 Integer>
typename EnableIf<IsIntegral<Integer>::value, Integer>::type operator|(
const Integer &defaultValue) const {
if (impl()->template is<double>())
return impl()->template as<Integer>();
else
return defaultValue;
}
private:
const TImpl *impl() const {
return static_cast<const TImpl *>(this);
}
};
}
}
} // namespace Internals
} // namespace ArduinoJson

View File

@ -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;