为什么自动i = same_const_variable无法推断出"const"? [英] why auto i = same_const_variable could not deduce "const"?

查看:145
本文介绍了为什么自动i = same_const_variable无法推断出"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 deduced A 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:
    — ...
    — If A is a cv-qualified type, the top level cv-qualifiers of A’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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆