Why does std::is_const<const int&>::value evaluate to false?
-
21-12-2019 - |
Question
This is a spin off of the question How to check if object is const or not?.
I was surprised to see the following program
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_const<const int&>::value << "\n";
}
produced this output
false
In what context does it make sense to think of const int&
as a non-const type?
Solution
Perhaps it'll be easier to understand with this example
std::cout << std::is_const<int const *>::value << "\n"; // pointer to const int
std::cout << std::is_const<int * const>::value << "\n"; // const pointer to int
Output:
false
true
The first type is a pointer to a const int
, while in the second the int *
itself is const
. Hence it results in true
while the former is false
. Similarly, what you have a reference to a const int
. If int& const
were valid it'd result in true
.
OTHER TIPS
A const
qualifier on a reference just means that the value can't be modified via the reference. It can still be modified by other means. For example:
int a = 1;
const int &b = a;
std::cout << b << std::endl; // Prints 1
a = 2;
std::cout << b << std::endl; // Prints 2
Thus, you can't assume that the value of a const
reference is actually constant.