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

旧城冷巷雨未停 提交于 2019-12-05 18:31:27

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.

Johannes Schaub - litb

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

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.

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