3

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

4

3 回答 3

3

一个很实际的答案是,“为什么要int选择?” 或者double,或者任何具有 int 单参数构造函数的 UDT?通过拒绝推断具体类型,编译器保留了更通用的初始化列表的任何可能应用。

于 2013-05-15T20:11:18.367 回答
3

另一方面,能够推断出initializer_list<X>forT是有吸引力的,以允许:

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

自从 EWG 关于初始化列表的讨论一开始就被认为是可取的行为。

T与其为与 {}-list 匹配的参数类型(我们在本文的早期草图和草稿中采用的选项)提出一个巧妙的推导规则,我们现在更愿意使用“auto”变量的特殊情况来处理这个问题当初始值设定项是 {}-list 时的推导。即,对于使用“auto”类型说明符和 {}-list 初始化程序声明的变量的特定情况,“auto”被推断为函数f(initializer_list<T>)而不是function f(T).

请参阅此 PDF 中的“模板参数推导”一章。http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2640.pdf

对于 C++14 之后,有一篇论文提出改变这些规则,以便单元素情况将类型推导为初始化器的类型。零元素和多元素的情况被提议成为病态的。http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3681.html

于 2013-05-19T21:30:17.220 回答
1

我认为原因是auto总是以相同的方式与初始化列表交互。换句话说,auto变量总是成为一个初始化列表,而不是在像这样的某些特殊情况下尝试推断出不同的类型。

于 2013-05-15T18:07:39.740 回答