From 49e961ca3598922f62ec9381dc1d742b4c1c0b31 Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Sat, 16 Nov 2024 21:02:52 +0200 Subject: ipa: libipa: vector: Generalize arithmetic operators Instead of hand-coding all arithmetic operators, implement them based on a generic apply() function that takes an operator-specific binary operators. This will simplify adding missing arithmetic operators. Signed-off-by: Laurent Pinchart Reviewed-by: Milan Zamazal --- src/ipa/libipa/vector.h | 52 ++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 20 deletions(-) (limited to 'src/ipa/libipa') diff --git a/src/ipa/libipa/vector.h b/src/ipa/libipa/vector.h index b8315dd0..5545da12 100644 --- a/src/ipa/libipa/vector.h +++ b/src/ipa/libipa/vector.h @@ -6,8 +6,10 @@ */ #pragma once +#include #include #include +#include #include #include @@ -66,36 +68,24 @@ public: return ret; } - constexpr Vector operator-(const Vector &other) const + constexpr Vector operator-(const Vector &other) const { - Vector ret; - for (unsigned int i = 0; i < Rows; i++) - ret[i] = data_[i] - other[i]; - return ret; + return apply(*this, other, std::minus<>{}); } - constexpr Vector operator+(const Vector &other) const + constexpr Vector operator+(const Vector &other) const { - Vector ret; - for (unsigned int i = 0; i < Rows; i++) - ret[i] = data_[i] + other[i]; - return ret; + return apply(*this, other, std::plus<>{}); } - constexpr Vector operator*(T factor) const + constexpr Vector operator*(T factor) const { - Vector ret; - for (unsigned int i = 0; i < Rows; i++) - ret[i] = data_[i] * factor; - return ret; + return apply(*this, factor, std::multiplies<>{}); } - constexpr Vector operator/(T factor) const + constexpr Vector operator/(T factor) const { - Vector ret; - for (unsigned int i = 0; i < Rows; i++) - ret[i] = data_[i] / factor; - return ret; + return apply(*this, factor, std::divides<>{}); } constexpr T dot(const Vector &other) const @@ -170,6 +160,28 @@ public: } private: + template + static constexpr Vector apply(const Vector &lhs, const Vector &rhs, BinaryOp op) + { + Vector result; + std::transform(lhs.data_.begin(), lhs.data_.end(), + rhs.data_.begin(), result.data_.begin(), + op); + + return result; + } + + template + static constexpr Vector apply(const Vector &lhs, T rhs, BinaryOp op) + { + Vector result; + std::transform(lhs.data_.begin(), lhs.data_.end(), + result.data_.begin(), + [&op, rhs](T v) { return op(v, rhs); }); + + return result; + } + std::array data_; }; -- cgit v1.2.1