Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add const to reference

I want to add const to a reference type by typedef const A B;.

Somehow it doesn't work. Is this not possible in c++?

Test:

#include <type_traits>
typedef int& A;
typedef const A B;  // <-- Add const
// typedef std::add_const<A>::type B;  // also doesn't work.
static_assert(std::is_const<typename std::remove_reference<
        B>::type>::value, "is const");
int main() {
    return 0;
}

Compilation Error:

add2.cpp:5:1: error: static assertion failed: is const
 static_assert(std::is_const<typename std::remove_reference<
 ^~~~~~~~~~~~~
like image 375
R zu Avatar asked May 01 '18 22:05

R zu


People also ask

Can references be const?

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.

How do I make a constant reference in C++?

By using the const keyword when declaring an lvalue reference, we tell an lvalue reference to treat the object it is referencing as const. Such a reference is called an lvalue reference to a const value (sometimes called a reference to const or a const reference).

Can reference variables be constant?

Once a reference variable has been defined to refer to a particular variable it can refer to any other variable. A reference is not a constant pointer.

Can you modify a const reference C++?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.


1 Answers

Somehow it doesn't work. Is this not possible in c++?

Not with the way you are doing it. typedef does not work like pre-processor macros.

typedef int& A;
typedef const A B;

does not translate to

typedef int& A;
typedef const int& B;

The const in

typedef const A B;

applies to A, not the int part of A. Since references are immutable in C++, const A is the same as A from a type point view.


You can use:

typedef int const& B;

If you want to derive it from A, you an use:

using B = typename std::remove_reference<A>::type const&;

If you are able to use C++14 or a later version, you can simplify that to:

using B = std::remove_reference_t<A> const&;
like image 121
R Sahu Avatar answered Oct 21 '22 05:10

R Sahu