Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 1.34 KB

332.md

File metadata and controls

57 lines (40 loc) · 1.34 KB
Info

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]());

https://godbolt.org/z/x3xa9erGE

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));

https://godbolt.org/z/4M9x1vjcG

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];
};

https://godbolt.org/z/PW3qvrnf6