Search code examples
c++c++11stlinitializer-liststdarray

Initialization of std::array with std::initializer_list in constructor's initialization list


Consider the following piece of code:

struct foo {
  std::vector<int> v;
  foo(std::initializer_list<int> L) : v{L} {}
};

The code above compiles fine and initializes v as expected. Now consider the following piece of code:

struct bar {
  std::array<int, 3> a;
  bar(std::initializer_list<int> L) : a{L} {}
};

The above piece of code gives a compile error.

error: no viable conversion from 'std::initializer_list' to 'int'

Searching the web I found that the "proper" way to initialize a member std::array with a std::list_initializer is to use reinterpret_cast in the following manner:

bar(std::initializer_list<int> L) : a(reinterpret_cast<std::array<int, 3> const&>(*(L.begin()))) {}

Q:

Why I can initialize a member std::vector with an std::initializer_list in the initialization list of a constructor but I can't a member std::array?

Is the work-around showed above with reinterpret_cast the proper way to initialize a member std::array with a std::initializer_list?


Solution

  • std::array was designed (in the Boost library) to support the braces initialization syntax with C++03. The only way to do that in C++03 was as a POD (plain old data) type, one with no constructors. Initializer lists were introduced in C++11, along with std::array, but std::array was not changed from its Boost version to use initializer lists. So, it's historical.

    By the way, note that the reinterpret_cast is dangerous here because the initializer list may contain fewer items than the array.