我想用fold表达式替换旧的meta递归函数,下面的meta函数是点积
如何替换下面的代码来折叠表达式?
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) + ...);
};
答案 0 :(得分:1)
有点琐碎:
template <T ... A, T ... B>
struct DotProduct<List<A...>, List<Head2, B...>>
{
constexpr static auto result = ((A * B) + ...);
};