Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can declare a const reference using type-alias?

Tags:

c++

reference

I have a simple question: As I know I can declare a const pointer to some datatype or a pointer to constant datatype but I can only declare a reference to a constant datatype only and no constant reference to a datatype; the fact that a reference is already constant because it cannot be rebound to another object.

So when I try to create a const ref to someDataType I get compile-time error. But the thing that matters me is when used with type alias using typedef or using. e.g:

#include <iostream>

int main() {

    int i{ 10 };
    //  int& const r1{ i }; // error: ‘const’ qualifiers cannot be applied to ‘int&’. Ok here.
    using rInt = int&; // or typedef int& rInt;
    const rInt r2{ i }; // why const is allowed here?
    ++r2; // this proves that the const is applied to the reference not to the object referred to.

    std::cout << r2 << std::endl; // 11

}

As you can see above I can add const to the reference which I think is Redundant in that context. But why C++ allows this with type-aliases but not directly?

like image 790
Alex24 Avatar asked Jan 31 '19 20:01

Alex24


People also ask

How do you declare a const reference in C++?

A variable can be declared as a reference by putting '&' in the declaration. int i = 10; // Reference to i. References to pointers is a modifiable value that's used same as a normal pointer.

Can you have a const reference C++?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

Is const reference type?

Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.

What is a type alias in C++?

Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.


1 Answers

Because the standard say so:

[dcl.ref] ... Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier ([dcl.type.simple]), in which case the cv-qualifiers are ignored

This is similar to how you cannot declare a reference reference, while it is possible through a typedef (where the references collapse into one):

int i;
int& iref = i;
//int& & irefref = iref; // not OK
using Iref = int&;
Iref& iretypedef = iref; // OK; collapses into int&

The CV-collapsing rules, just like reference collapsing rules are essential to make templates and type deductions usable.

like image 63
eerorika Avatar answered Sep 21 '22 20:09

eerorika