9
#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?

Taher A. Ghaleb
  • 5,120
  • 5
  • 31
  • 44
Denis
  • 2,786
  • 1
  • 14
  • 29
  • 2
    Is [this](https://stackoverflow.com/questions/44695684/structured-bindings-when-something-looks-like-a-reference-and-behaves-similarly) answers your question? – W.F. Nov 24 '18 at 20:03

1 Answers1

9

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 ]

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160