模板类中引用的引用的类型是什么

What is the type of a reference of a reference in a template class

本文关键字:引用 是什么 类型      更新时间:2023-10-16

在下面的代码中,a和b的类型是什么?

template <class T = const int&>
struct A
{
T& a;
T b;
};
int main() {
int i = 1;
A<> a{i, i};
return 1;
}

我使用了这篇文章中的代码,它可以给出变量的类型。 ->帖子

但是,它说这两种类型都是i const&.

int main() {
int i = 1;
A<> a{i, i};
std::cout << type_name<decltype(a.a)>() << std::endl;
std::cout << type_name<decltype(a.b)>() << std::endl;
return 0;
}

在上述情况下,T&T是同一类型吗?

这些与号组合在一起并成为 r 值还是其他规则?

Tconst int&因为这就是你告诉它的。

T&也是const int&,因为引用折叠会将T&转换为T

[dcl.ref]/6:如果typedef-name([dcl.typedef], [temp.param]) 或decltype-specifier([dcl.type.simple]) 表示对类型T的引用的类型TR,则尝试创建类型 ">lvalue引用 cvTR" 会创建类型 "lvalue 引用 toT",而尝试创建类型 "对cvTR的 rvalue 引用" 会创建类型TR[ 注意:此规则称为引用折叠。— 尾注 ][ 示例:

int i;
typedef int& LRI;
typedef int&& RRI;
LRI& r1 = i;                    // r1 has the type int&
const LRI& r2 = i;              // r2 has the type int&
const LRI&& r3 = i;             // r3 has the type int&
RRI& r4 = i;                    // r4 has the type int&
RRI&& r5 = 5;                   // r5 has the type int&&
decltype(r2)& r6 = i;           // r6 has the type int&
decltype(r2)&& r7 = i;          // r7 has the type int&

— 结束示例 ]

这是为了方便起见,因为没有const int& &这样的东西(引用引用;不要与确实存在的右值引用类型混淆const int&&!),并且能够像您一样编写代码而不必手动"摆脱"额外的"&,这很方便。

此处更详细地解释了此规则背后的基本原理:

  • 对要求的参考折叠规则的简明解释:(1
  • ) A&&&-> A& , (2) A&&&&-> A& , (3) A&& -> A& 和 (4) A&& &&&-> A&&