Why would they special-case certain initializer lists instead of treating them all the same?

倖福魔咒の 提交于 2020-01-13 14:12:10

问题


Say I have a variable auto x that I want to initialize to 7 using brace initialization, simple:

auto x {7};

Except I learned that x is NOT an integer, but an initialization list itself. Why? Is there a specific reason why the committee would decide that auto should grab the initialization list in the case of a single auto value, or do they expect us to just realize these shouldn't be used together. I cant seem to think of a possible reason i would want an initializer list to be stored into auto as opposed to the value


回答1:


A very practical answer is, "why should int be selected?" Or double, or any UDT with an int single-argument constructor? By declining to deduce a concrete type, the compiler preserves any possible application of the more general initializer list.




回答2:


On the other hand, being able to deduce an initializer_list<X> for T is attractive to allow:

auto x = { 1, 1, 2, 3, 5 };  
f(x);   
g(x); 

which was deemed desirable behavior since the very beginning of the EWG discussions about initializer lists.

Rather than coming up with a clever deduction rule for a parameter type T matched with a {}-list (an option we pursued in earlier sketches and drafts of this paper), we now prefer to handle this with a special case for "auto" variable deduction when the initializer is a {}-list. I.e., for the specific case of a variable declared with an "auto" type specifier and a {}-list initializer, the "auto" is deduced as for a function f(initializer_list<T>) instead of as for a function f(T).

See chapter "Template argument deduction" in this PDF. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2640.pdf

For the after-C++14, there is a paper that proposes to change these rules so that the one-element case deduces the type to the type of the initializer. The zero and multiple element case is proposed to become ill-formed. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3681.html




回答3:


I assume that the reason is that so auto always interacts with initialization lists in the same way. In other words, the auto variable always becomes an initialization list rather than trying to deduce a different type in certain special cases like this one.



来源:https://stackoverflow.com/questions/16571725/why-would-they-special-case-certain-initializer-lists-instead-of-treating-them-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!