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<
^~~~~~~~~~~~~
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.
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).
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.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
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&;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With