简体   繁体   中英

convert 'std::initializer_list<int>' to 'int'

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'

}
  • Why there is not implicit conversation? (edit: because v is list )) )
  • Why v is list and is not int ?

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?

"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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM