Search code examples
c++referencetypedef

Why is it possible to define a reference to a reference using type alias?


Since it is not possible to define a reference to a reference, why is the 8th line of this code not throwing an error? My understanding is that the aforementioned statement is equivalent to double &&ref2 = value; which should throw an error.

#include <iostream>
using namespace std;
int main()
{
    double value = 12.79;
    typedef double& ref_to_double;
    ref_to_double ref = value;        // Equivalent to double &ref = value;
    ref_to_double &ref2 = value;      
    ref2 = 12.111;
    cout << value << endl;        
}

Output:

12.111

Follow-up question: Replacing the 8th line with ref_to_double &&ref2 = value; is also not producing a compile-time error. Why is this so?


Solution

  • Why is it possible to define a reference to a reference using type alias?

    is also not producing a compile-time error. Why is this so?

    why is the 8th line of this code not throwing an error?

    Because the language allows such expressions to be valid, there is no other explanation... Let's take the nice example from the standard, from c++draft/Declarations/References:

    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&