Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::is_const<const int&>::value evaluate to false?

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?

like image 806
R Sahu Avatar asked Jun 04 '14 05:06

R Sahu


People also ask

What is the difference between int const* and int int*?

The first const keyword can go either side of data type, hence int const* is equivalent to const int*. We provide nothing but the best curated videos and practice problems for our students.

What happens when a function is declared as const in C++?

An object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object. When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.

Can We pass a non-const variable to a const function?

There is no substantial issue to pass const or non-const variable to the function because the value that will be returned by the function will be constant automatically. As the argument of the function is non-const. For const return type and const parameter: Here, both return type and parameter of the function are of const types.

What is the use of is_const in C++?

std:: is_const. std:: is_const. If T is a const-qualified type (that is, const, or const volatile ), provides the member constant value equal to true. For any other type, value is false . The behavior of a program that adds specializations for is_const or is_const_v (since C++17) is undefined.


1 Answers

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.

like image 61
Praetorian Avatar answered Nov 04 '22 03:11

Praetorian