0

If you write a template like this one

template <typename T> using X = const T; 

what's the meaning of const T?

To know about it I wrote this program:

std::cout << std::boolalpha << std::is_same_v<X<int&>, int&> << '\n' << std::is_same_v<X<const int*>, const int* const> << '\n' << std::is_same_v<X<const int&>, const int&> << '\n'; 

and for my surprise all the answers were true.

Why X < int&> is an int& and not a 'const int&'?

I compiled it with gcc 7.3.0 and clang++ 6.0. Same answer.

1
  • This is simply how stuff works. If T is "pointer to int" (int *), then it's reasonable for const T to be "const pointer to int" (int *const), rather than "pointer to const int" (const int *). Commented Mar 10, 2019 at 15:56

2 Answers 2

4

A reference to const int is one thing. A const reference to an int is nonsense.

Under the rules of C++, when you const qualify a reference, nothing happens.

This makes lots of sense if you are used to east const, and little if you are a west const user.

int const& 

is a reference to a const int.

int&const 

is the same as

int& 
Sign up to request clarification or add additional context in comments.

2 Comments

"east const" "west const" Hah!
@holyblack east const best const west const worst const. (Say that 5 times fast)
1

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. [ Example:

typedef int& A; const A aref = 3; // ill-formed; lvalue reference to non-const initialized with rvalue 

The type of aref is “lvalue reference to int”, not “lvalue reference to const int”. — end example ]

[dcl.ref]/1

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.