How can I conveniently initialize array of function pointers?

Viewed 69
template<int I>;
void f(int value) { }

constexpr std::array<void(*)(int), 100> f_pointers = { &f<0>, &f<1>, &f<2>, ... &f<99> };

How can we fill f_pointers 0 ... 99 without typing them all out? Expecting the answer to involve std::integer_sequence unpacking, but reading pack expansion doesn't make it obvious how to expand in this way. Working in C++20.

2 Answers
#include <array>
#include <utility>


template<int N>
void f(){}

template<int... Indices>
constexpr auto create_functions(std::integer_sequence<int, Indices...>)
{
    return std::array {f<Indices>...};
}

constexpr auto arr = create_functions(std::make_integer_sequence<int, 100>{});

int main()
{
    return 0;
}

You could write it like this:

template<std::size_t ... I>
constexpr auto generate_fs(std::index_sequence<I...>) {
    return std::array { &f<I> ... };
}

int main() {
    constexpr std::array<void(*)(int), 100> f_pointers = [] { 
        return generate_fs(std::make_index_sequence<100>{}); 
    }();
}

Here's a demo.

Related