Add specialization for unsigned scalar add/sub

Adding/subtracting an unsigned scalar to a signed vector should maintain
the same signed vector

Fixes https://gitlab.com/kicad/code/kicad/-/issues/18212
This commit is contained in:
Seth Hillbrand 2024-06-14 17:26:21 -07:00
parent 7ea013b96c
commit 6df16d053e
2 changed files with 26 additions and 3 deletions

View File

@ -439,6 +439,13 @@ VECTOR2<std::common_type_t<T, U>> operator+( const VECTOR2<T>& aLHS, const U& aS
} }
template <class T>
VECTOR2<T> operator+( const VECTOR2<T>& aVector, std::unsigned_integral auto aScalar )
{
return VECTOR2<T>( aVector.x + aScalar, aVector.y + aScalar );
}
template <class T, class U> template <class T, class U>
VECTOR2<std::common_type_t<T, U>> operator-( const VECTOR2<T>& aLHS, const VECTOR2<U>& aRHS ) VECTOR2<std::common_type_t<T, U>> operator-( const VECTOR2<T>& aLHS, const VECTOR2<U>& aRHS )
{ {
@ -452,6 +459,12 @@ VECTOR2<std::common_type_t<T, U>> operator-( const VECTOR2<T>& aLHS, const U& aS
return VECTOR2<std::common_type_t<T, U>>( aLHS.x - aScalar, aLHS.y - aScalar ); return VECTOR2<std::common_type_t<T, U>>( aLHS.x - aScalar, aLHS.y - aScalar );
} }
template <class T>
VECTOR2<T> operator-( const VECTOR2<T>& aVector, std::unsigned_integral auto aScalar )
{
return VECTOR2<T>( aVector.x - aScalar, aVector.y - aScalar );
}
template <class T> template <class T>
VECTOR2<T> VECTOR2<T>::operator-() VECTOR2<T> VECTOR2<T>::operator-()

View File

@ -154,12 +154,22 @@ BOOST_AUTO_TEST_CASE( test_casting )
BOOST_CHECK_EQUAL( vlong, VECTOR2L( -5, -4 ) ); BOOST_CHECK_EQUAL( vlong, VECTOR2L( -5, -4 ) );
BOOST_CHECK_EQUAL( vfloat, VECTOR2<float>( -5.0f, -4.0f ) ); BOOST_CHECK_EQUAL( vfloat, VECTOR2<float>( -5.0f, -4.0f ) );
vint = vint - 1u;
vdouble = vdouble - 1u;
vlong = vlong - 1u;
vfloat = vfloat - 1u;
BOOST_CHECK_EQUAL( vint, VECTOR2I( -6, -5 ) );
BOOST_CHECK_EQUAL( vdouble, VECTOR2D( -6.0, -5.0 ) );
BOOST_CHECK_EQUAL( vlong, VECTOR2L( -6, -5 ) );
BOOST_CHECK_EQUAL( vfloat, VECTOR2<float>( -6.0f, -5.0f ) );
auto add = vint + vdouble; auto add = vint + vdouble;
BOOST_CHECK_EQUAL( add, VECTOR2D( -10.0, -8.0 ) ); BOOST_CHECK_EQUAL( add, VECTOR2D( -12.0, -10.0 ) );
auto sub = vint - 2 * vlong; auto sub = vint - 2 * vlong;
BOOST_CHECK_EQUAL( sub.x, 5 ); BOOST_CHECK_EQUAL( sub.x, 6 );
BOOST_CHECK_EQUAL( sub.y, 4 ); BOOST_CHECK_EQUAL( sub.y, 5 );
vunsigned = VECTOR2<unsigned>( std::numeric_limits<unsigned>::max(), std::numeric_limits<unsigned>::max() ); vunsigned = VECTOR2<unsigned>( std::numeric_limits<unsigned>::max(), std::numeric_limits<unsigned>::max() );
vint = VECTOR2I( vunsigned ); vint = VECTOR2I( vunsigned );