Skip to content

Commit

Permalink
fix operator+ being picked for 3rd party types (nholthaus#299)
Browse files Browse the repository at this point in the history
  • Loading branch information
BenjaminNavarro committed Nov 18, 2022
1 parent 3ca0e22 commit e586885
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion include/units.h
Original file line number Diff line number Diff line change
Expand Up @@ -2503,7 +2503,7 @@ namespace units
// LINEAR ARITHMETIC
//------------------------------

template<class UnitTypeLhs, class UnitTypeRhs, std::enable_if_t<!traits::is_same_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
template<class UnitTypeLhs, class UnitTypeRhs, std::enable_if_t<traits::is_unit_t<UnitTypeLhs>::value && traits::is_unit_t<UnitTypeRhs>::value && !traits::is_same_scale<UnitTypeLhs, UnitTypeRhs>::value, int> = 0>
constexpr inline int operator+(const UnitTypeLhs& /* lhs */, const UnitTypeRhs& /* rhs */) noexcept
{
static_assert(traits::is_same_scale<UnitTypeLhs, UnitTypeRhs>::value, "Cannot add units with different linear/non-linear scales.");
Expand Down
19 changes: 19 additions & 0 deletions unitTests/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<typename Unit>
Foo operator+(const unit_t<Unit>&) const {
return Foo{};
}
};

struct Bar : Foo {
// operator+ is implicitly inherited
};

}

TEST_F(UnitContainer, unitTypeAddition)
{
// units
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit e586885

Please sign in to comment.