简体   繁体   English

如何方便地初始化函数指针数组?

[英]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?我们如何填充 f_pointers 0 ... 99 而不将它们全部输入? Expecting the answer to involve std::integer_sequence unpacking, but reading pack expansion doesn't make it obvious how to expand in this way.期望答案涉及std::integer_sequence解包,但阅读包扩展并没有使如何以这种方式扩展很明显。 Working in C++20.在 C++20 中工作。

#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 .这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM