Last active
April 2, 2023 12:36
-
-
Save SebastianWilke/df6905d687a931f08f57a6be1d41e5c9 to your computer and use it in GitHub Desktop.
C++ compile time dot product using template metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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