0

我想用折叠表达式替换旧的元递归函数,下面的元函数是点积

如何替换以下代码以折叠表达式?

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

使用类似这样的伪代码

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

更清洁的版本

 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) + ...);
  };
4

1 回答 1

1

这有点微不足道:

template <T ... A, T ... B>
struct DotProduct<List<A...>, List<Head2, B...>>
{
    constexpr static auto result = ((A * B) + ...);
};
于 2018-07-19T15:55:15.357 回答