Reputation: 55
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) + ...);
};
Upvotes: 0
Views: 310
Reputation: 96761
It is somewhat trivial:
template <T ... A, T ... B>
struct DotProduct<List<A...>, List<Head2, B...>>
{
constexpr static auto result = ((A * B) + ...);
};
Upvotes: 1