std::array
in C++11 is a useful class that provides a C++ Container interface over a C stack array.
But why does std::array
not have the typical fill constructor that most containers have? Instead, it has a method fill
.
Is there some reason why std::array
is unique among STL containers in this regard?
From section 23.3.2.1:
An array is an aggregate (8.5.1) that can be initialized with the syntax array a = { initializer-list };
If it worked like std::vector
it wouldn't be a POD anymore. Additionally from the same section:
The conditions for an aggregate (8.5.1) shall be met.
These conditions are:
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equalinitializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
Yes; std::array
is meant to be an aggregate (C++11 §8.5.1) so that at can be used in as many contexts as possible where a plain array can be used. An aggregate can have no explicit constructors or destructor.
Everybody's explained the "why" pretty well I think, so I'll just put up a workaround suggestion, which should compile to be just as good as a native constructor:
template< typename T, std::size_t n > std::array<T,n> filledArray( const T& v ) {
std::array<T,n> r;
r.fill( v );
return r;
}
auto arr = filledArray<int,4>( 7 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With