为什么在const T&中使用const? T是引用类型时参数消失吗? [英] Why does the const in a const T& parameter disappear when T is a reference type?

查看:80
本文介绍了为什么在const T&中使用const? T是引用类型时参数消失吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码显示,如果使用引用类型(例如int&)实例化带有ref-to- const参数的模板,则该参数不是const:

The following code shows that if a template taking a ref-to-const parameter is instantiated with a reference type (e.g., int&), the parameter isn't const:

#include <iostream>

template<typename T>
void f(const T& arg)         // arg isn't const if T is a reference type
{
  arg = -1;
}

int main()
{
  int x = 0;
  f<int&>(x);                // instantiate f with reference type
  std::cout << x << '\n';    // prints -1 under gcc, clang, and msvc
}

这是怎么回事?

我的猜测是arg的初始类型是int & const &,并且以某种方式转换为int&.如果是这样的话,那么就标准而言,这究竟是怎么发生的呢?如果这不是怎么回事,那是什么?

My guess is that the initial type of arg is int & const & and that this somehow transforms to int&. If that's so, exactly how does that happen, in terms of the standard? If that's not what's going on, what is?

推荐答案

感谢来自莫斯科的弗拉德 C ++的答案:具有显式的模板函数指定引用类型作为类型参数,我相信const -disappearance的关键是8.3.2/1,它表示:

Thanks to Vlad from Moscow's answer to C++: template function with explicitly specified reference type as type parameter, I believe the crux of the const-disappearance is 8.3.2/1, which says:

在声明T D中,D具有以下两种形式之一
& attribute-specifier-seqopt D1
&& attribute-specifier-seqopt D1
并且声明T D1中的标识符类型为 " derived-declarator-type-list T",然后是标识符D的类型 是对T的派生声明符类型列表引用".可选的 attribute-specifier-seq 属于引用类型.简历合格 引用格式不正确,除非引入了简历限定符 通过使用 typedef-name (7.1.3,14.1)或 decltype-specifier (7.1.6.2),在这种情况下,cv限定词将被忽略.

In a declaration T D where D has either of the forms
& attribute-specifier-seqoptD1
&& attribute-specifier-seqoptD1
and the type of the identifier in the declaration T D1 is "derived-declarator-type-list T," then the type of the identifier of D is "derived-declarator-type-list reference to T." The optional attribute-specifier-seq appertains to the reference type. Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specifier (7.1.6.2), in which case the cv-qualifiers are ignored.

我已经整理了相关文字. (我想按照标准格式设置整个段落的格式,但是我不知道如何获得正确的缩进和添加下标.)

I've emboldened the relevant text. (I'd like to format the entire paragraph as it is in the standard, but I can't figure out how to get the right indentation and to add subscripting.)

const消失后,正常的参考折叠就会像往常一样出现.

Once the const disappears, normal reference collapsing kicks in as usual.

这篇关于为什么在const T&amp;中使用const? T是引用类型时参数消失吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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