Reputation: 1896
Why I can not use variable assigned using "initializer_list" as "normal" variable?
code:
void stovr(int a){}
int main() {
auto v {5}; // v is std::initializer_list<int>
stovr(v); // cannot convert 'std::initializer_list<int>' to 'int'
}
v
is list )) )v
is list
and is not int
?Upvotes: 3
Views: 1499
Reputation: 13013
"A braced initializer has no type! A braced initializer has no type! A braced initializer has no type! No type corresponds to braced initializer"
(C) Scott Meyers.
This is why auto type deduction of brace-initializer with one element fails to follow intuitive rules in C++11 and C++14.
It is considered a defect in standard by many programmers. That is why proposal N3922: New Rules for auto deduction from braced-init-list exists. Notably:
For direct list-initialization:
- For a braced-init-list with only a single element, auto deduction will deduce from that entry;
- For a braced-init-list with more than one element, auto deduction will be ill-formed.
Not sure if it is a breaking change and will all C++14 code work after this.
Source: There was a good talk on CppCon about quirks of type deduction in C++11/C++14/C++17 by Scott Meyers: link, including brace-initializer auto type deduction (starting from 29:00). Same thing in more details in his new book (and there was a free sampler with that chapter as well)
Upvotes: 2
Reputation:
std::initializer_list<T>
cannot convert to T
for the same reason that T[]
cannot convert to T
, and vector<T>
cannot convert to T
: if you merely know that you have a std::initializer_list<T>
, you don't know how many elements it has.
std::initializer_list<int> x = { 1, 2, 3 };
is perfectly valid. If there were an implicit conversion from std::initializer_list<int>
to int
, which of the values would you expect to see?
Upvotes: 7