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
For ar, here's an approach:
namespace detail {
template
constexpr auto make_iota_array(T const offset, std::integer_sequence) noexcept
-> std::array {
return {{(Ns + offset)...}};
}
}
template
constexpr auto make_iota_array(T const offset = {}) noexcept {
static_assert(N >= T{}, "no negative sizes");
return detail::make_iota_array(offset, std::make_integer_sequence{});
}
// ...
auto ar = make_iota_array(99);
Online Demo
For ar2, here's an approach:
namespace detail {
template
constexpr auto generate_array(F& f, std::index_sequence)
-> std::array {
return {{f(std::integral_constant{})...}};
}
}
template
constexpr auto generate_array(F f) {
return detail::generate_array(f, std::make_index_sequence{});
}
// ...
auto ar2 = generate_array([](auto i) -> C { return {i, i * 1.12f}; });
Online Demo
(noexcept is more-or-less optional here IMO, and omitted here for brevity, but is present in the demos.)
N.b. both are fully constexpr, but since generate_array is likely to be used with lambdas it won't be constexpr in practice until C++17 (demo). Also n.b. generate_array will work with non-copyable/non-movable types in C++17 due to guaranteed copy elision (demo).