template<typename T, std::size_t N>
struct DotProductT {
static inline T result(T* a, T* b) {
return *a * *b + DotProduct<T, N-1>::result(a+1,b+1);
}
};
// partial specialization as end criteria
template<typename T>
struct DotProductT<T, 0> {
static inline T result(T*, T*) {
return T{};
}
};
Some thoughts about the example (c++).
In general this pattern is often used. This special example has
the disadvantage,
that the type T and the size N must be in any case explicitely
declared in the call
DotProduct<int,3>::result(...). So here are two alternatives
- dp1 and dp2.
The first one uses fold expressions in combination with variadic
templates and the
second "if constexpr" for breaking the recursion.
(btw. inline is default within the struct)
#include <cstddef>
#include <iostream>
#include <utility>
namespace detail {
template<typename T,std::size_t N, std::size_t... I>
T dp_(T (&a)[N], T (&b)[N],
std::index_sequence<I...>) {
return ((a[I] * b[I])+...);
}
}
template<typename T, std::size_t N>
T dp1(T (&a)[N], T (&b)[N]) {
return detail::dp_(a,b,std::make_index_sequence<N>{});
}
template<std::size_t P, std::size_t N, typename T>
T dp2(T (&a)[N], T (&b)[N]) {
if constexpr (N == P) { return T{0}; } else {
return a[P] * b[P] + dotprod<P+1>(a,b);
}
}
int main()
{
int a[] = {1,2,3};
int b[] = {4,5,6};
std::cerr << dp2<0>(a,b) << std::endl;
std::cerr << dp1(a,b) << std::endl;
return 0;
}
--
You received this message because you are subscribed to the Google Groups "ats-lang-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ats-lang-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ats-lang-users/0d199a8d-e203-457a-b77b-10223c634dd8o%40googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ats-lang-users/4afd5374-c2f5-7aec-9762-d464c7c015c1%40bejocama.de.
To view this discussion on the web visit https://groups.google.com/d/msgid/ats-lang-users/CAPPSPLoYVWfJ9WFSVqj9bd1ACakHA-uJ6o4Y%2Bn2e2io-EB1L1w%40mail.gmail.com.
--
You received this message because you are subscribed to a topic in the Google Groups "ats-lang-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ats-lang-users/nPH1DNJRkKI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ats-lang-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ats-lang-users/CAHjn2Kx6febCVhJ7fs5GT-nZW2tGOi0x97qdFrCb7GtdeV2zUA%40mail.gmail.com.