模板类中引用的引用的类型是什么
What is the type of a reference of a reference in a template class
在下面的代码中,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 值还是其他规则?
T
const 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&&
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 在C++17中,引用const字符串的语义应该是什么
- 引用文件的适当方法是什么?
- 引用 std::any 或 not_yet_in_std::whatever 的惯用方式是什么?
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 通过引用函数传递指针参数是什么意思?
- C++ 中的引用范围是什么?
- 将引用绑定到指针的语法是什么?(各种)
- 对struct::struct的未定义引用是什么意思
- 使用对函数和IO对象的引用(作为参数)的目的是什么
- 将字段(在类中)定义为引用的缺点是什么?
- (.text+0x20):对"主要"的未定义引用是什么意思
- 将此类传递给引用的正确语法是什么?
- 引用 using 声明引入的功能的句子是什么意思?
- 使用 std::shared_ptr 接收变量作为引用的利弊是什么?
- std::forward() 的右值引用重载的目的是什么?
- 模板类中引用的引用的类型是什么
- 引用和指向常量的指针的用法是什么
- 通过引用查找调用范围的标准引用是什么
- 模板类型的引用是什么意思?