From 25bad04a70e71344159a4496104149e99cd74708 Mon Sep 17 00:00:00 2001 From: Matthew Mott Date: Sat, 3 Apr 2021 15:48:57 +0100 Subject: [PATCH] Add test for scalar multiplication of Vector3 Also fix the operator* definition with appropriate use of std::is_arithmetic to allow scalar multiplication in either order (pre or post) without triggering ambiguous overload errors. --- libs/math/Vector3.h | 12 +++++++++--- test/math/Vector3.cpp | 11 +++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/libs/math/Vector3.h b/libs/math/Vector3.h index f73389919d..c4c91e7b47 100644 --- a/libs/math/Vector3.h +++ b/libs/math/Vector3.h @@ -423,7 +423,10 @@ class BasicVector3 }; /// Multiply vector components with a scalar and return the result -template +template < + typename T, typename S, + typename = typename std::enable_if::value, S>::type +> BasicVector3 operator*(const BasicVector3& v, S s) { T factor = static_cast(s); @@ -431,8 +434,11 @@ BasicVector3 operator*(const BasicVector3& v, S s) } /// Multiply vector components with a scalar and return the result -template -BasicVector3 operator*(T s, const BasicVector3& v) +template < + typename T, typename S, + typename = typename std::enable_if::value, S>::type +> +BasicVector3 operator*(S s, const BasicVector3& v) { return v * s; } diff --git a/test/math/Vector3.cpp b/test/math/Vector3.cpp index fef13e1942..206a565cc3 100644 --- a/test/math/Vector3.cpp +++ b/test/math/Vector3.cpp @@ -117,6 +117,17 @@ TEST(MathTest, SubtractVector4) EXPECT_EQ(v1 - v2, Vector4(-0.125, 92, 449.5, -93.5)); } +TEST(MathTest, ScalarMultiplyVector3) +{ + Vector3 vec(2, 4, -5); + + EXPECT_EQ(vec * 2, Vector3(4, 8, -10)); + EXPECT_EQ(2 * vec, Vector3(4, 8, -10)); + + EXPECT_EQ(vec * 0.5, Vector3(1, 2, -2.5)); + EXPECT_EQ(0.5 * vec, Vector3(1, 2, -2.5)); +} + TEST(MathTest, Vector3AsCArray) { Vector3 vec(256, -10, 10000);