From e586885c590e06227352a44ec31ba8ffead7d02c Mon Sep 17 00:00:00 2001 From: Benjamin Navarro Date: Fri, 18 Nov 2022 15:35:53 +0100 Subject: [PATCH] fix operator+ being picked for 3rd party types (#299) --- include/units.h | 2 +- unitTests/main.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/include/units.h b/include/units.h index 3a956f5d..6e321bd7 100644 --- a/include/units.h +++ b/include/units.h @@ -2503,7 +2503,7 @@ namespace units // LINEAR ARITHMETIC //------------------------------ - template::value, int> = 0> + template::value && traits::is_unit_t::value && !traits::is_same_scale::value, int> = 0> constexpr inline int operator+(const UnitTypeLhs& /* lhs */, const UnitTypeRhs& /* rhs */) noexcept { static_assert(traits::is_same_scale::value, "Cannot add units with different linear/non-linear scales."); diff --git a/unitTests/main.cpp b/unitTests/main.cpp index 96befa34..0a9dc5be 100644 --- a/unitTests/main.cpp +++ b/unitTests/main.cpp @@ -927,6 +927,22 @@ TEST_F(UnitContainer, make_unit) EXPECT_EQ(meter_t(5), dist); } +namespace test { + +// Test types for https://github.com/nholthaus/units/issues/299 +struct Foo { + template + Foo operator+(const unit_t&) const { + return Foo{}; + } +}; + +struct Bar : Foo { + // operator+ is implicitly inherited +}; + +} + TEST_F(UnitContainer, unitTypeAddition) { // units @@ -963,6 +979,9 @@ TEST_F(UnitContainer, unitTypeAddition) d = 1.0 + scalar_t(1.0); EXPECT_NEAR(2.0, d, 5.0e-6); + + test::Bar bar; + bar + a_m; } TEST_F(UnitContainer, unitTypeUnaryAddition)