GodBolt
Consider the following code snippet:
using A = void(*)(int);
A foo(const void* ptr)
{
return reinterpret_cast<A>(ptr);
}
GCC 10 likes this just fine. clang++-10, however, says this is an error!
<source>:5:12: error: reinterpret_cast from 'const void *' to 'A' (aka 'void
(*)(int)') casts away qualifiers
return reinterpret_cast<A>(ptr);
^~~~~~~~~~~~~~~~~~~~~~~~
Functions aren't mutable in C++ (and C), and there are no "const functions". So why is clang++ complaining here?
Because the standard says so.
[expr.reinterpret.cast]/2:
The
reinterpret_cast
operator shall not cast away constness.
[expr.const.cast]/7:
A conversion from a type
T1
to a typeT2
casts away constness ifT1
andT2
are different, there is a cv-decomposition ofT1
yielding n such thatT2
has a cv-decomposition of the formand there is no qualification conversion that converts
T1
to
Here T1 is const void*
, T2 is void (*)(int)
, n = 1, the cv-decomposition of T2
has cv0 = "", P0 = "pointer to", cv1 = "", U2 = void(int)
, so the corresponding version of T1
is void*
. There is no qualification conversion from const void*
to void*
. It follows that the conversion casts away constness and cannot be performed by reinterpret_cast
.
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