From [expr.const.cast]/3:
For two similar types T1 and T2, a prvalue of type T1 may be explicitly converted to the type T2 using a const_cast if, considering the cv-decompositions of both types, each Pi1 is the same as Pi2 for all i. The result of a const_cast refers to the original entity.
It seems that const cast to non-pointer non-reference type is allowed. For example, the following function
void f(int a)
{
const_cast<int>(a);
}
should be well-formed, since int
and int
are certainly similar types and have no Pi in their cv-decompositions (thus the proposition that "each Pi1 is the same as Pi2 for all i" should be true).
However, both GCC and Clang reject the code above (see Compiler Explorer). The error messages are
Clang:
<source>: In function 'void f(int)':
<source>:3:22: error: invalid use of const_cast with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type
3 | const_cast<int>(a);
| ^
GCC:
<source>: In function 'void f(int)':
<source>:3:5: error: invalid use of 'const_cast' with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type
3 | const_cast<int>(a);
| ^~~~~~~~~~~~~~~~~~
Am I missing something or is it a compiler bug?
UPDATE: this doesn't work, either:
void f()
{
const_cast<int>(int{});
}