Info
-
Did you know that in C++ you can generate jump tables at compile-time?
Example
template<auto N> constexpr auto foo() { return N; }
constexpr std::array jump_table{
foo<0>,
foo<1>,
foo<2>,
};
static_assert(0 == jump_table[0]());
static_assert(1 == jump_table[1]());
static_assert(2 == jump_table[2]());
Puzzle
- Can you implemnt dispatch fn which generates jump table for given N?
template<auto N> constexpr auto foo() { return N; }
template<auto N = 42>
constexpr auto dispatch(auto n); // TODO
static_assert(1 == dispatch(1));
static_assert(7 == dispatch(7));
static_assert(23 == dispatch(23));
Solutions
template <auto N = 42>
constexpr auto dispatch(auto n) -> int {
using foo_return_type = std::invoke_result<decltype(&foo<0>)>::type;
const auto jump_table = []<auto... I>(std::index_sequence<I...>) {
return std::array<foo_return_type, sizeof...(I)>{(foo<I>())...};
}(std::make_index_sequence<N>{});
return jump_table[n];
};