如何在 C++ 中实现两个向量的编译时乘积

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

两个大小为 'N' 的向量的标量积定义为 SP(a, b) = a_1 * b_1 + ... + a_N * b_N.

编译时整数向量定义为:

template<int... I>
struct Vector;

函数产品接口:

template<typename Vector1, typename Vector2>
constexpr int product

例如,可以使用以下代码进行测试:

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

如何实现产品来匹配上面的断言和接口?

也许是这样的:

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

使用 C++17 折叠

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);
 }

没有 C++17 折叠表达式,通过使用函数重载。

template <int... Ele>
struct vector {};

template <int Ele1, int Ele2>
constexpr int DotProd(vector<Ele1> v1, vector<Ele2> v2) {
    return Ele1 * Ele2;
}

template <int Ele1First, int... Ele1, int Ele2First, int... Ele2>
constexpr int DotProd (vector<Ele1First, Ele1...> v1, vector<Ele2First, Ele2...> v2) {
    return (Ele1First * Ele2First) + DotProd(vector<Ele1...>{}, vector<Ele2...> {});
}

int main() {
   
    vector<1, 2, 3, 4> v1;
    vector<4, 3, 2, 1> v2;

    static_assert (DotProd(v1, v2) == 20);
    return 0;
}