Skip to content

Instantly share code, notes, and snippets.

Embed
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 >
constexpr
std::array<decltype(std::declval<F>()(size_t(0))),sizeof...(Ns)>
generate_array( F&& f, std::index_sequence<Ns...> )
{
return { f(Ns)... };
}
template < size_t N, class F >
constexpr
std::array<decltype(std::declval<F>()(size_t(0))),N>
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
You can’t perform that action at this time.