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
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