Skip to content

Instantly share code, notes, and snippets.

@SebastianWilke
Last active April 2, 2023 12:36
Show Gist options
  • Save SebastianWilke/df6905d687a931f08f57a6be1d41e5c9 to your computer and use it in GitHub Desktop.
Save SebastianWilke/df6905d687a931f08f57a6be1d41e5c9 to your computer and use it in GitHub Desktop.
C++ compile time dot product using template metaprogramming
#include <array>
#include <cstddef> // std::size_t
template <std::size_t N, std::size_t M = 0U>
struct dotprod {
template <typename InputIt1, typename InputIt2, typename T>
constexpr static T sum(InputIt1 u, InputIt2 v, T init) {
const T uv_m{*(u + M) * T{*(v + M)}};
return uv_m + dotprod<N, M + 1U>::sum(u, v, init);
}
};
template <std::size_t N>
struct dotprod<N, N> {
template <typename InputIt1, typename InputIt2, typename T>
constexpr static T sum(InputIt1, InputIt2, T init) {
return init;
}
};
int main() {
constexpr std::array u{1U, 2U, 3U};
constexpr std::array v{4U, 5U, 6U};
static_assert(dotprod<3U>::sum(begin(u), begin(v), 3U) == 35U);
static_assert(dotprod<3U, 1U>::sum(begin(u), begin(v), 3U) == 31U);
static_assert(dotprod<3U, 2U>::sum(begin(u), begin(v), 3U) == 21U);
static_assert(dotprod<3U, 3U>::sum(begin(u), begin(v), 3U) == 3U);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment