简体   繁体   中英

c++17 fold expression dot product simpfily

I want replace old meta recursive function with fold expression, the below meta function is the dot product

How do I replace this following code to fold expression?

constexpr static auto result = Head1 * Head2 + DotProduct<List<Tail1...>, List<Tail2...>>::result;

with pseudo code something like this

constexpr static auto result = Head1 * Head2 + (Tail1... * Tail2...)



template <typename List1, typename List2>
  struct DotProduct;

  template <T Head1, T Head2, T... Tail1, T... Tail2>
  struct DotProduct< List<Head1, Tail1...>, List<Head2, Tail2...> >
  {
    constexpr static auto result = Head1 * Head2 + 
    //constexpr static auto result = Head1 * Head2 + DotProduct<List<Tail1...>, List<Tail2...>>::result;
  };

  template <T Head1, T Head2>
  struct DotProduct< List<Head1>, List<Head2>>
  {
    constexpr static auto result = Head1 * Head2;
  };

  template <T... Head1, T... Head2>
  struct DotProduct< List<Head1...>, List<Head2...>>
  {
    //return result as the default constructor of T (most cases : 0)
    constexpr static auto result = T();
    /* to check if both lists are the same size. This will cause a compile
    failure if the 2 lists are of unequal size. */
    using CheckIfSameSize = 
      typename std::enable_if<sizeof...(Head1) == sizeof...(Head2)>::type;
  };

Cleaner version

 template <typename List1, typename List2>
  struct DotProduct;

  template <T ...Head1, T ...Head2>
  struct DotProduct< List<Head1...>, List<Head2...> >
  {
    if constexpr(sizeof...(Head1) == sizeof...(Head2))
      constexpr static auto result = ((Head1 * Head2) + ...);
  };

It is somewhat trivial:

template <T ... A, T ... B>
struct DotProduct<List<A...>, List<Head2, B...>>
{
    constexpr static auto result = ((A * B) + ...);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM