Can I initialize an array using the std::initializer_list
object instead of brace-enclosed initializer?
As known, we can do this: http://en.cppreference
As far I know, no: you can't initialize a std::array
with a std::initializer_list
.
The problem is that std::array
is intended as a lightweight replacement (a wrapper) for the classic C-style array. So light that is without constructors, so only implicit constructor can be used.
The construction with aggregate initialization (via implicit constructor) is possible because it's possible for the C-style array.
But std::initializer_list
is a class, more complicated than an aggregate inizialization.
You can initialize, by example, a std::vector
with a std::initializer_list
but only because there is an explicit constructor, for std::vector
, that receive a std::initializer_list
. But std::vector
is a heavier class.
The only solution that I see is a 2 step way: (1) construction and (2) copy of the std::initializer_list
values. Something like
std::array arr5;
auto ui = 0U;
auto cit = il.cbegin();
while ( (ui < arr5.size()) && (cit != il.cend()) )
arr5[ui++] = *cit++;
p.s.: sorry for my bad English.