Skip to content

Instantly share code, notes, and snippets.

@tk3369
Last active May 24, 2026 04:32
Show Gist options
  • Select an option

  • Save tk3369/09630ff534d02ce39e0d8b68e5b8727a to your computer and use it in GitHub Desktop.

Select an option

Save tk3369/09630ff534d02ce39e0d8b68e5b8727a to your computer and use it in GitHub Desktop.
#include <array>
#include <cstddef>
#include <utility>
// Compile-time-sized body, equivalent to foo(::Val{N})
template <std::size_t N>
double foo_impl() {
std::array<double, N> v; // stack, size known at compile time
for (std::size_t i = 0; i < N; ++i) v[i] = work(i);
return reduce(v); // can be fully unrolled / vectorized
}
// Build a static jump table over [0, MaxN]
template <std::size_t... Is>
constexpr auto make_table(std::index_sequence<Is...>) {
return std::array<double(*)(), sizeof...(Is)>{ &foo_impl<Is>... };
}
template <std::size_t MaxN>
double foo(std::size_t n) {
static constexpr auto table =
make_table(std::make_index_sequence<MaxN + 1>{});
return table[n](); // O(1) indirect call into specialized code
}
// call site
double r = foo<32>(runtime_n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment