How to construct an std::array with index sequence?

后端 未结 2 1147
我在风中等你
我在风中等你 2020-12-14 07:55

How can I construct an std::array with an index sequence, or a lambda which depends on a sequential index?

std::iota and std::generat

2条回答
  •  春和景丽
    2020-12-14 08:24

    The next approach should work for you:

    template
    constexpr auto create_array_impl(std::index_sequence) {
        return std::array{ {I...} };
    }
    
    template
    constexpr auto create_array() {
        return create_array_impl(std::make_index_sequence{});
    }
    

    You can create an array like:

    constexpr auto array = create_array();
    

    wandbox example

    One can modify the aforementioned solution to add a lambda in the next way:

    template
    constexpr auto create_array_impl(F&& func, std::index_sequence) {
        return std::array{ {func(I)...} };
    }
    
    template
    constexpr auto create_array(F&& func) {
        return create_array_impl(std::forward(func), std::make_index_sequence{});
    }
    

    And then use:

    const auto array = create_array([](auto e) {
        return e * e;
    });
    

    wandbox example

提交回复
热议问题