【问题标题】:c++17 fold expression dot product simpfilyc++17折表达式点积化简
【发布时间】:2018-07-19 15:49:30
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ c++17 fold-expression


    【解决方案1】:

    这有点微不足道:

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

    【讨论】:

    • 感谢现在看起来更干净和简单以防止不同大小的列表可以使用 if constexpr 检查相同然后执行 constexpr static auto result = ((A * B) + ...);
    • @user3770234 你可以static_assert(sizeof...(A) == sizeof...(B))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2011-08-16
    • 2018-06-25
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多