📜 ⬆️ ⬇️

C ++ 17 auto output changes during curly initialization

The latest C ++ 17 standard is implemented in GCC7 (to be adopted this year). I would like to note that the output rules of the auto type have changed during curly initialization.

C ++ 11, C ++ 14 - the following rules were used for type inference:

int foo(){ return 1; } auto x = foo(); // x = int auto x{foo()}; // x = initializer_list<int> 

The difference between ordinary and figured initialization was unintuitive and strange. It also looked unintuitive with the initial capture.

Scott Myers draws attention to this in his book .
')
 [x = foo()](){} // x = int [x{foo()}](){} // x = initializer_list<int> 

Inference of type of return value, partially solved this problem.

 auto f() { return {1,2}; //   , {1,2}     } 

But the situation manifests itself again in the case of a separate auto variable.

 auto f() { auto x{1,2}; // x = initializer_list<int> return x; //   initializer_list,       } 

In C ++ 17 for curly initialization, the rules are now as follows:

1. With curly initialization with only one element, the type will be inferred from the type of this element.

 auto x { 1 }; // x = int 

2. With curly initialization with several elements, the output will be impossible.

 auto x1 { 1, 2 }; // :        auto 

3. With curly initialization with one or more elements and an assignment, the type will be displayed as std :: initializer_list

  auto x = { 1, 2 }; // x = std::initializer_list<int> 

Offer
Standard draft - 7.1.7.4.1 Placeholder type deduction

PS In the comments, we found out that the change made to the standard is slightly different from the original sentence. Corrected the article.

Source: https://habr.com/ru/post/319474/


All Articles