C++ Logo


Advanced search

Re: [std-proposals] Allow reinterpret_cast in constexpr when C-cast is allowed

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Fri, 27 May 2022 09:30:50 -0600
On Fri, 27 May 2022 at 09:05, Oleksandr Koval <oleksandr.koval.dev_at_[hidden]>

> The C-style cast and reinterpret_cast are not the same. A C-style cast
>> can perform a static_cast and const_cast; a reinterpret_cast can perform
>> the identity conversion but after that performs conversions that cannot
>> appear in constant evaluation.
> C-cast has multiple stages and some of them are allowed in constexpr
> context. reinterpret_cast also has multiple stages but none of them are
> allowed in constexpr, what's the logic here? Why is the same conversion
> allowed with one syntax and not with the other?

Yes, it's an inconsistency. However, reinterpret_cast can perform the
following conversions:
* (2) identity
* (4/5) pointer-integer
* (6) function pointer
* (7) object pointer (storage, via void*)
* (8) function-object pointer
* (10) pointer-to-member
* (11) reference (storage)
Only the first is sensible to appear in constant evaluation, so the
inconsistency is minor. And it's trivial to determine in meta when a
conversion is the identity conversion.

If your argument is that reinterpret_cast as identity conversion should be
>> allowed to appear in constant evaluation, that might make sense, but it's
>> hard to see that as much of an improvement over being explicit with if
>> constexpr. That is, it's beneficial reading the code to see when it will
>> perform the weaker, safer operation.
> Not only identity but all conversions that are allowed for C-cast in
> constexpr context.

reinterpret_cast cannot perform conversions involving static_cast or
const_cast, only the identity conversion. See above.

> I see your point but honestly I can hardly imagine anyone will write
> if-constexpr or explicitly two versions of such a function using enable-if
> in pre-C++17 when a simple C-cast does the work.

 Why would we care about old versions of the standard? If you want to code
golf that's on you.

Received on 2022-05-27 15:31:02