[RFC,05/11] ipa: libipa: vector: Generalize arithmetic operators
diff mbox series

Message ID 20241117221712.29616-6-laurent.pinchart@ideasonboard.com
State Superseded
Headers show
Series
  • Improve linear algebra helpers in libipa
Related show

Commit Message

Laurent Pinchart Nov. 17, 2024, 10:17 p.m. UTC
Instead of hand-coding all arithmetic operators, implement them based on
a generic apply() function that takes an operator-specific
std::function. This will simplify adding missing arithmetic operators.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
---
 src/ipa/libipa/vector.h | 48 ++++++++++++++++++++++++-----------------
 1 file changed, 28 insertions(+), 20 deletions(-)

Patch
diff mbox series

diff --git a/src/ipa/libipa/vector.h b/src/ipa/libipa/vector.h
index 9dabdc28a540..8c4edfbaf85f 100644
--- a/src/ipa/libipa/vector.h
+++ b/src/ipa/libipa/vector.h
@@ -74,36 +74,24 @@  public:
 		return ret;
 	}
 
-	constexpr Vector<T, Rows> operator-(const Vector<T, Rows> &other) const
+	constexpr Vector operator-(const Vector &other) const
 	{
-		Vector<T, Rows> ret;
-		for (unsigned int i = 0; i < Rows; i++)
-			ret[i] = data_[i] - other[i];
-		return ret;
+		return apply(*this, other, [](T a, T b) { return a - b; });
 	}
 
-	constexpr Vector<T, Rows> operator+(const Vector<T, Rows> &other) const
+	constexpr Vector operator+(const Vector &other) const
 	{
-		Vector<T, Rows> ret;
-		for (unsigned int i = 0; i < Rows; i++)
-			ret[i] = data_[i] + other[i];
-		return ret;
+		return apply(*this, other, [](T a, T b) { return a + b; });
 	}
 
-	constexpr Vector<T, Rows> operator*(T factor) const
+	constexpr Vector operator*(T factor) const
 	{
-		Vector<T, Rows> ret;
-		for (unsigned int i = 0; i < Rows; i++)
-			ret[i] = data_[i] * factor;
-		return ret;
+		return apply(*this, factor, [](T a, T b) { return a * b; });
 	}
 
-	constexpr Vector<T, Rows> operator/(T factor) const
+	constexpr Vector operator/(T factor) const
 	{
-		Vector<T, Rows> ret;
-		for (unsigned int i = 0; i < Rows; i++)
-			ret[i] = data_[i] / factor;
-		return ret;
+		return apply(*this, factor, [](T a, T b) { return a / b; });
 	}
 
 	constexpr T dot(const Vector<T, Rows> &other) const
@@ -178,6 +166,26 @@  public:
 	}
 
 private:
+	static constexpr Vector apply(const Vector &lhs, const Vector &rhs, std::function<T(T, T)> func)
+	{
+		Vector result;
+		std::transform(lhs.data_.begin(), lhs.data_.end(),
+			       rhs.data_.begin(), result.data_.begin(),
+			       func);
+
+		return result;
+	}
+
+	static constexpr Vector apply(const Vector &lhs, T rhs, std::function<T(T, T)> func)
+	{
+		Vector result;
+		std::transform(lhs.data_.begin(), lhs.data_.end(),
+			       result.data_.begin(),
+			       [&func, rhs](T v) { return func(v, rhs); });
+
+		return result;
+	}
+
 	std::array<T, Rows> data_;
 };