Type of variables in structured binding

  • A+
Category:Languages
#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 } 

What is the consequential difference between identifiers ref1 and ref2 in that example? As I understand, ref2 in structure binding also has a reference type, but why does decltype indicate a non-referenced type for it?

 


decltype(e) behaves differently depending on what e is given as the argument. For the structured binding, decltype yields what follows, [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

The referenced type for a structured binding declaration with an array type expression as the initializer is the type of the element [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 ]

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: