2

suppose I have

typedef int& intr;
typedef intr& intrr;

I am allowed to declare

int x = 7;
intrr y = x;

But what is a reference-to-reference? Is an intrr any different semantically than just an intr?

Matt G
  • 1,661
  • 19
  • 32
  • hmm, another related question: [Concise explanation of reference collapsing rules requested: (1) A& & -> A& , (2) A& && -> A& , (3) A&& & -> A& , and (4) A&& && -> A&&](http://stackoverflow.com/q/13725747) – AliciaBytes Nov 27 '14 at 02:51

1 Answers1

1

There's no such thing as a reference to reference. The C++ standard explicitly says so:

§8.3.3/5

There shall be no references to references, ...

In typedefs and templates, there is a rule commonly referred to as "reference collapsing". It's described in paragraph 6 of the same section:

If a typedef (7.1.3), a type template-parameter (14.3.1), or a decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a type T, an attempt to create the type “lvalue reference to cv TR” creates the type “lvalue reference to T”, while an attempt to create the type “rvalue reference to cv TR” creates the type TR.

[ Example:

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&

end example ]

intr and intrr in your sample are exactly the same type, which is int&.

#include <iostream>
#include <type_traits>

int main()
{
    typedef int& intr;
    typedef intr& intrr;
    int x = 7;
    intrr y = x;
    std::cout << std::is_same<intr, intrr>::value;
    std::cout << std::is_same<int&, intrr>::value;
    std::cout << std::is_same<int&, intr>::value;
}

Output: 111

Thomas Becker's article on Rvalue References explained provides a nice table:

  1. A& & becomes A&
  2. A& && becomes A&
  3. A&& & becomes A&
  4. A&& && becomes A&&