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

问题描述 投票:0回答:2

[大小为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);

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

c++ templates constexpr compile-time
2个回答
1
投票

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

1
投票

也许像这样:

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

© www.soinside.com 2019 - 2024. All rights reserved.