How to construct std::array object with initializer list? [duplicate]
An std::array<>
has no constructor that takes an std::initializer_list<>
(initializer list constructor) and there is no special language support for what it may mean to pass a std::initializer_list<>
to a class' constructors such that that may work. So that fails.
For it to work, your derived class needs to catch all elements and then forward them, a constructor template:
template<typename ...E>
enum_addressable_array(E&&...e) : base_t{{std::forward<E>(e)...}} {}
Note that you need {{...}}
in this case because brace elision (omitting braces like in your case) does not work at that place. It's only allowed in declarations of the form T t = { ... }
. Because an std::array<>
consists of a struct embedding a raw array, that will need two level of braces. Unfortunately, I believe that the exact aggregate structure of std::array<>
is unspecified, so you will need to hope that it works on most implementations.
Since a std::array
is a structure that contains an aggregate (it is not an aggregate itself, and does not have a constructor that takes a std::initializer_list
), you can initialize the underlying aggregate inside the structure with an initializer list using a double-braces syntax like so:
std::array<int, 4> my_array = {{1, 2, 3, 4}};
Note that this is not using std::initializer_list
... this is simply using a C++ initializer list to initialize the publicly accessible array member of std::array
.