问题
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>
forT
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 functionf(initializer_list<T>)
instead of as for afunction 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