c++ - Initialization of std::array with std::initializer_list in constructor's initialization list -
this question has answer here:
consider following piece of code:
struct foo { std::vector<int> v; foo(std::initializer_list<int> l) : v{l} {} };
the code above compiles fine , initializes v
expected. consider 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 compile error.
error: no viable conversion 'std::initializer_list' 'int'
searching web found "proper" way initialize member std::array
std::list_initializer
use reinterpret_cast
in following manner:
bar(std::initializer_list<int> l) : a(reinterpret_cast<std::array<int, 3> const&>(*(l.begin()))) {}
q:
why can initialize member std::vector
std::initializer_list
in initialization list of constructor can't member std::array
?
is work-around showed above reinterpret_cast
proper way initialize member std::array
std::initializer_list
?
std::array
designed (in boost library) support braces initialization syntax c++03. way in c++03 pod (plain old data) type, 1 no constructors. initializer lists introduced in c++11, along std::array
, std::array
not changed boost version use initializer lists. so, it's historical.
by way, note reinterpret_cast
dangerous here because initializer list may contain fewer items array
.
Comments
Post a Comment