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?
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.
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.
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.
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.
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
.
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