Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement compile time product of two vectors in C++

The scalar product of two vectors with size 'N' defined as SP(a, b) = a_1 * b_1 + ... + a_N * b_N.

Compile-time integer vector defined as:

template<int... I>
struct Vector;

Function product interface:

template<typename Vector1, typename Vector2>
constexpr int product

For example, following code could be used for test:

static_assert(product<Vector<1, 2, 5>, Vector<1, 3, 4>> == 27);

How can product be implemented to match the assert and interface above?

like image 810
Antonio Ferreiro Avatar asked Nov 02 '25 06:11

Antonio Ferreiro


2 Answers

With C++17 folding

template <int...>
struct Vector
 { };

template <typename, typename>
constexpr int product = -1;

template <int ... Is, int ... Js>
constexpr int product<Vector<Is...>, Vector<Js...>> = (... + (Is*Js));

int main ()
 {
   static_assert(product<Vector<1, 2, 5>, Vector<1, 3, 4>> == 27);
 }
like image 127
max66 Avatar answered Nov 03 '25 20:11

max66


Maybe something like this:

template<int ... >
struct Vector{};

template<int ... Idx1, int ... Idx2>
constexpr int product(Vector<Idx1...>, Vector<Idx2...>) {
    static_assert(sizeof...(Idx1) == sizeof...(Idx2), "Product cannot be calculated, dims dismatched");
    int res = 0;
    int temp [] = { (res +=  (Idx1 * Idx2),0)...};
    static_cast<void>(temp);
    return res;
}

int main() {
    static_assert(product(Vector<1,2,5>{},Vector<1,3,4>{}) == 27);
}

Live demo

like image 27
rafix07 Avatar answered Nov 03 '25 22:11

rafix07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!