结构化绑定中的变量类型
Type of variables in structured binding
#include <type_traits>
int main()
{
int arr[1] = { 6 };
auto& ref1 = arr[0];
static_assert( std::is_same_v<decltype( ref1 ), int&> ); //ok
auto& [ ref2 ] = arr;
static_assert( std::is_same_v<decltype( ref2 ), int> ); //ok
static_assert( std::is_same_v<decltype( ref2 ), int&> ); //error
}
在该示例中,标识符 ref1
和 ref2
之间的相应区别是什么?据我了解,结构绑定中的 ref2
也有引用类型,但为什么 decltype
表示它是非引用类型?
decltype(e)
的行为因参数 e
的不同而不同。对于结构化绑定,decltype
产生以下内容,[dcl.type.simple]:
For an expression e
, the type denoted by decltype(e)
is defined as follows:
- if
e
is an unparenthesized id-expression naming a structured binding, decltype(e)
is the referenced type as given in the specification of the structured binding declaration
以数组类型表达式作为初始值设定项的结构化绑定声明的引用类型是元素的类型[dcl.struct.bind]:
If E
is an array type with element type T
, the number of elements in the identifier-list shall be equal to the number of elements of E
. Each vi is the name of an lvalue that refers to the element i of the array and whose type is T
; the referenced type is T
. [ Note: The top-level cv-qualifiers of T are cv. — end note ]
#include <type_traits>
int main()
{
int arr[1] = { 6 };
auto& ref1 = arr[0];
static_assert( std::is_same_v<decltype( ref1 ), int&> ); //ok
auto& [ ref2 ] = arr;
static_assert( std::is_same_v<decltype( ref2 ), int> ); //ok
static_assert( std::is_same_v<decltype( ref2 ), int&> ); //error
}
在该示例中,标识符 ref1
和 ref2
之间的相应区别是什么?据我了解,结构绑定中的 ref2
也有引用类型,但为什么 decltype
表示它是非引用类型?
decltype(e)
的行为因参数 e
的不同而不同。对于结构化绑定,decltype
产生以下内容,[dcl.type.simple]:
For an expression
e
, the type denoted bydecltype(e)
is defined as follows:
- if
e
is an unparenthesized id-expression naming a structured binding,decltype(e)
is the referenced type as given in the specification of the structured binding declaration
以数组类型表达式作为初始值设定项的结构化绑定声明的引用类型是元素的类型[dcl.struct.bind]:
If
E
is an array type with element typeT
, the number of elements in the identifier-list shall be equal to the number of elements ofE
. Each vi is the name of an lvalue that refers to the element i of the array and whose type isT
; the referenced type isT
. [ Note: The top-level cv-qualifiers of T are cv. — end note ]