为什么自动i = same_const_variable无法推断出"const"? [英] why auto i = same_const_variable could not deduce "const"?
问题描述
const int ci = 10;
auto i = ci; // i will be "int" instead of "const int"
i = 20;
我想知道为什么汽车是为这种行为而设计的?
I am wondering why auto is designed for this kind of behaviour?
为什么类型i是"int"而不是"const int"?
why the type i is "int" instead of "const int" ?
这里有什么问题?
我认为了解为什么会帮助我们记住它
I think understand why will help us to remember it
推荐答案
auto
大多数遵循与模板参数推导相同的类型推导规则.唯一的区别是,在某些情况下,auto
将从 braised-init-list 中推断出std::initializer_list
,而模板参数推导则不这样做.
auto
mostly follows the same type deduction rules as template argument deduction. The only difference is that auto
will deduce std::initializer_list
from a braced-init-list in some cases, while template argument deduction doesn't do this.
来自N3337,§7.1.6.4[dcl.spec.auto]
6 ...然后为变量
d
推导的类型为 使用从函数调用(14.8.2.1)的模板参数推导规则确定的推导A
,...
6 ... The type deduced for the variable
d
is then the deducedA
determined using the rules of template argument deduction from a function call (14.8.2.1), ...
您观察到的行为与从函数调用中推导类型时模板自变量推导的行为相同
The behavior you're observing is the same as what template argument deduction would do when deducing types from a function call
§14.8.2.1[temp.deduct.call]
2 如果
P
不是引用类型:
-... ...
—如果A
是具有简历资格的类型,则类型为A
的顶级cv限定词将被忽略,以进行类型推导.
2 If
P
is not a reference type:
— ...
— IfA
is a cv-qualified type, the top level cv-qualifiers ofA
’s type are ignored for type deduction.
因此,在
auto i = ci;
顶级const
限定词将被忽略,而i
被推导为int
.
the top level const
qualifier is ignored and i
is deduced as int
.
写作时
auto& i = ci;
然后,i
不再不是引用类型,并且以上规则不适用,因此保留了const
限定符.
then i
is no longer not a reference type and the above rule doesn't apply, so the const
qualifier is retained.
这篇关于为什么自动i = same_const_variable无法推断出"const"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!