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

时间:2019-05-09 16:59:50

标签: c++ templates reference-type

在下面的代码中,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&

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值或其他规则?

1 个答案:

答案 0 :(得分:2)

Tconst int&,因为这就是您所说的。

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

  

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

此规则背后的原理在此处进行了详细说明:

相关问题