Skip to content

Commit

Permalink
Use a const reference in is_convertible()
Browse files Browse the repository at this point in the history
  • Loading branch information
bblanchon committed Sep 21, 2024
1 parent cd4b2b2 commit 48ee4a1
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
1 change: 1 addition & 0 deletions extras/tests/Misc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ add_executable(MiscTests
arithmeticCompare.cpp
conflicts.cpp
issue1967.cpp
issue2129.cpp
JsonString.cpp
NoArduinoHeader.cpp
printable.cpp
Expand Down
55 changes: 55 additions & 0 deletions extras/tests/Misc/issue2129.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// ArduinoJson - https://arduinojson.org
// Copyright © 2014-2024, Benoit BLANCHON
// MIT License

#include <ArduinoJson.h>
#include <catch.hpp>

template <typename T>
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<float>::invalid_value_ = std::numeric_limits<float>::lowest();

template <typename T>
void convertToJson(const Nullable<T>& src, JsonVariant dst) {
if (src.is_valid()) {
dst.set(src.value());
} else {
dst.clear();
}
}

TEST_CASE("Issue #2129") {
Nullable<float> nullable_value = Nullable<float>{123.4f};

JsonDocument doc;

doc["value"] = nullable_value;

REQUIRE(doc["value"].as<float>() == Approx(123.4f));
}
2 changes: 1 addition & 1 deletion src/ArduinoJson/Polyfills/type_traits/is_convertible.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 48ee4a1

Please sign in to comment.