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_castoperator shall not cast away constness.
[expr.const.cast]/7:
A conversion from a type
T1to a typeT2casts away constness ifT1andT2are different, there is a cv-decomposition ofT1yielding n such thatT2has a cv-decomposition of the formand there is no qualification conversion that converts
T1to
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