Skip to content

Commit

Permalink
BasicVector4 subtraction operators are now non-members
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew Mott committed Sep 8, 2021
1 parent 54511a8 commit b8b1e3c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 22 deletions.
42 changes: 20 additions & 22 deletions libs/math/Vector4.h
Expand Up @@ -100,28 +100,6 @@ class BasicVector4
return !(*this == other);
}

/* Define the substraction operators - and -= with any other BasicVector4 of type OtherElement
* The vectors are substracted from each other element-wise
*/
template<typename OtherElement>
BasicVector4<Element> operator- (const BasicVector4<OtherElement>& other) const {
return BasicVector4<Element>(
_v[0] - static_cast<Element>(other.x()),
_v[1] - static_cast<Element>(other.y()),
_v[2] - static_cast<Element>(other.z()),
_v[3] - static_cast<Element>(other.w())
);
}

template<typename OtherElement>
BasicVector4<Element>& operator-= (const BasicVector4<OtherElement>& other) {
_v[0] -= static_cast<Element>(other.x());
_v[1] -= static_cast<Element>(other.y());
_v[2] -= static_cast<Element>(other.z());
_v[3] -= static_cast<Element>(other.w());
return *this;
}

/* Define the multiplication operators * and *= with another Vector4 of type OtherElement
*
* The vectors are multiplied element-wise
Expand Down Expand Up @@ -276,6 +254,26 @@ BasicVector4<T>& operator+=(BasicVector4<T>& v1, const BasicVector4<T>& v2)
return v1;
}

/// Componentwise subtraction of two vectors
template<typename T>
BasicVector4<T> operator- (const BasicVector4<T>& v1, const BasicVector4<T>& v2)
{
return BasicVector4<T>(v1.x() - v2.x(),
v1.y() - v2.y(),
v1.z() - v2.z(),
v1.w() - v2.w());
}

template<typename T>
BasicVector4<T>& operator-= (BasicVector4<T>& v1, const BasicVector4<T>& v2)
{
v1.x() -= v2.x();
v1.y() -= v2.y();
v1.z() -= v2.z();
v1.w() -= v2.w();
return v1;
}

/// Multiply BasicVector4 with a scalar
template <
typename T, typename S,
Expand Down
8 changes: 8 additions & 0 deletions test/math/Vector.cpp
Expand Up @@ -219,7 +219,15 @@ TEST(MathTest, SubtractVector4)
Vector4 v1(0, 96, 457, -3.5);
Vector4 v2(0.125, 4, 7.5, 90);

// Subtract and return
EXPECT_EQ(v1 - v2, Vector4(-0.125, 92, 449.5, -93.5));
EXPECT_EQ(v2 - v2, Vector4());

// Subtract in place
auto v1Copy = v1;
v1 -= v2;
EXPECT_NE(v1, v1Copy);
EXPECT_EQ(v1, Vector4(-0.125, 92, 449.5, -93.5));
}

TEST(MathTest, ScalarMultiplyVector3)
Expand Down

0 comments on commit b8b1e3c

Please sign in to comment.