Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Create arrays of no-default-constructible elements with std::generate like syntax.
#include <array>
#include <utility>
template < class F, size_t... Ns >
generate_array( F&& f, std::index_sequence<Ns...> )
return { f(Ns)... };
template < size_t N, class F >
generate_array( F&& f ) {
return generate_array( std::forward<F>(f), std::make_index_sequence<N>() );
// Usage example
struct A {
constexpr explicit A(int i) : _i(i) {}
int _i;
// Define functor. Constexpr lambda expressions are C++17 or later.
constexpr A generator( size_t i ) { return A(i); }
extern constexpr std::array<A,10> a = generate_array<10>( generator );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment