7

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< ^~~~~~~~~~~~~ 

2 Answers 2

15

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&; 
Sign up to request clarification or add additional context in comments.

2 Comments

West const loses again.
@Yakk, this is the first time I am hearing of that expression. Thanks for that.
0

Unfortunately std::add_const<T> doesn't do what you think for references. The way to add const to a reference is this:

 using in_type = double&; using out_type = std::add_lvalue_reference_t<std::add_const_t<std::remove_reference_t<in_type>>>; static_assert( std::is_same<out_type, double const&>{} , "!"); 

I got bitten by this again and found my own answer a year later. Even wanted to vote it up :).

This is a bit more general and more concise, but still not perfect.

 using in_type = Ref; using out_type = decltype( std::as_const(std::declval<in_type>())); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.