Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializer_list with auto contains multiple expressions

Rather simple question,

auto x11 {1,2,3,4};
auto x1 = {1,2,3,4};
auto x22 {1.0, 2.25, 3.5};
auto x2 = {1.0, 2.25, 3.5};

As far as I understand, there should be no difference here with respect to having = or not. However, using llvm/clang 6.0.0 (with --std=c++17), I get :

main1.cpp:35:17: error: initializer for variable 'x11' with type 'auto' contains multiple
  expressions
auto x11 {1,2,3,4};
~~~~~~~~    ^

main1.cpp:37:20: error: initializer for variable 'x22' with type 'auto' contains multiple
  expressions
auto x22 {1.0, 2.25, 3.5};

From Stroustroup's C++ book, page.162:

auto x1 {1,2,3,4}; // x1 is an initializer_list<int>
auto x2 {1.0, 2.25, 3.5 }; // x2 is an initializer_list of<double>

So, is there really a problem in not having = in there?

like image 433
Viktor Khristenko Avatar asked Jul 04 '18 06:07

Viktor Khristenko


1 Answers

The rule of auto type deduction changed since N3922. (This is considered as a defect in C++14).

In direct-list-initialization (but not in copy-list-initalization), when deducing the meaning of the auto from a braced-init-list, the braced-init-list must contain only one element, and the type of auto will be the type of that element:

auto x1 = {3}; // x1 is std::initializer_list<int>
auto x2{1, 2}; // error: not a single element
auto x3{3};    // x3 is int
               // (before N3922 x2 and x3 were both std::initializer_list<int>)

So before N3922, all the variables in your sample work fine and have type std::initializer_list<int>. But since N3922, for direct initialization (i.e. for x11 and x22) the braced-initializer must contain only one element (and their type would be the type of the element), then the code become ill-formed.

See N3922 and N3681 for more.

like image 144
songyuanyao Avatar answered Oct 16 '22 05:10

songyuanyao