【问题标题】:How can I conveniently initialize array of function pointers?如何方便地初始化函数指针数组?
【发布时间】:2020-12-24 17:17:03
【问题描述】:
template<int I>;
void f(int value) { }

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

我们如何填写 f_pointers 0 ... 99 而无需全部输入?期待答案涉及std::integer_sequence 解包,但阅读pack expansion 并不能说明如何以这种方式扩展。使用 C++20 工作。

【问题讨论】:

    标签: c++ templates variadic-templates c++20


    【解决方案1】:
    #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;
    }
    

    【讨论】:

    • 如此简单!不知道我们是如何错过f&lt;Indices&gt;... 语法的……使用 lambda 可以更小。将此标记为答案,因为您先到达那里。
    【解决方案2】:

    你可以这样写:

    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>{}); 
        }();
    }
    

    这是demo

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      相关资源
      最近更新 更多