Search code examples
c++templatesvariadic-templatesc++20

How can I conveniently initialize array of function pointers?


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.


Solution

  • #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;
    }