Skip to content

Commit

Permalink
Add test for scalar multiplication of Vector3
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Matthew Mott committed Apr 3, 2021
1 parent 1a74920 commit 25bad04
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
12 changes: 9 additions & 3 deletions libs/math/Vector3.h
Expand Up @@ -423,16 +423,22 @@ class BasicVector3
};

/// Multiply vector components with a scalar and return the result
template <typename T, typename S>
template <
typename T, typename S,
typename = typename std::enable_if<std::is_arithmetic<S>::value, S>::type
>
BasicVector3<T> operator*(const BasicVector3<T>& v, S s)
{
T factor = static_cast<T>(s);
return BasicVector3<T>(v.x() * factor, v.y() * factor, v.z() * factor);
}

/// Multiply vector components with a scalar and return the result
template <typename T>
BasicVector3<T> operator*(T s, const BasicVector3<T>& v)
template <
typename T, typename S,
typename = typename std::enable_if<std::is_arithmetic<S>::value, S>::type
>
BasicVector3<T> operator*(S s, const BasicVector3<T>& v)
{
return v * s;
}
Expand Down
11 changes: 11 additions & 0 deletions test/math/Vector3.cpp
Expand Up @@ -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);
Expand Down

0 comments on commit 25bad04

Please sign in to comment.