【问题标题】:What is the type of a reference of a reference in a template class [duplicate]模板类中引用的引用类型是什么[重复]
【发布时间】:2019-05-09 16:59:49
【问题描述】:

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

template <class T = const int&>
struct A
{
    T& a;
    T b;
};

int main() {
    int i = 1;
    A<> a{i, i};
    return 1;
}

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

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

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&amp;T 是同一类型吗?

这些 & 符号是否结合并成为 r 值或其他规则?

【问题讨论】:

  • 同意。这可能不是最好的副本,但它解释了参考折叠规则。 TL;DR:& 符号确实结合,但它们形成左值引用,而不是右值引用。
  • 我个人认为作为交叉引用比欺骗更好,但无论如何:)

标签: c++ templates reference-type


【解决方案1】:

Tconst int&amp;,因为这是你告诉它的。

T&amp; 也是const int&amp; 因为引用折叠 将您的T&amp; 转换为T

[dcl.ref]/6: 如果是 typedef-name ([dcl.typedef], [temp.param]) 或 decltype-specifier ([dcl.type.simple ]) 表示类型 TR 是对类型 T 的引用,尝试创建类型“对 cv TR 的左值引用”会创建类型“对@987654333 的左值引用@”,而尝试创建类型“对 cv TR 的右值引用”会创建类型 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&amp; &amp; 之类的东西(引用引用;不要与确实存在的右值引用类型 const int&amp;&amp; 混淆!)并且能够编写类似的代码很方便您无需手动“摆脱”“额外”&amp;

这里更详细地解释了这条规则背后的基本原理:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2011-01-15
    相关资源
    最近更新 更多