C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 27 May 2022 10:14:33 -0400
On Fri, May 27, 2022 at 9:59 AM Oleksandr Koval via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> That is, in:
>
> template<typename To, typename From>
> constexpr To cast(From p){
> return (To)p; // #1
> // return reinterpret_cast<To>(p); // #2
> }
>
> line #2 should work in constexpr context in all cases where #1 works, in other cases it should be not an error but just a non-constexpr function.

C-style casts are defined to work by basically trying a bunch of
different casts, in order, and whichever the first one is that works
is what gets done. If a C-style cast works in constexpr code, it is
*only* because it picked a `static_cast`, not a `reinterpret_cast`.

And if that's the case, there's no reason to use `reinterpret_cast`
here. You're writing `constexpr` code, so you already know that it
*must* use `static_cast`, so that's what you should have written.

As for just making it a non-constexpr function... no. Keeping
`reinterpret_cast` out of `constexpr` code (even if it isn't
technically `constexpr`, you still prefixed the function with it) is
an inherently good thing. We shouldn't open that door even a crack.

> Note that I don't propose to silently make the function non-constexpr when it contains reinterpret_cast, this should be allowed only in generic context, when types are not known.
>
> reinterpret_cast is generally preferred over C-cast but in some generic code reinterpret_cast doesn’t work. If you wonder about use-case, I have an array-like wrapper around memory buffer. Type of element is not always the same as the type of a buffer's byte. I want to mark my functions `constexpr` and have them actually `constexpr` only when types match.

You can do that (in a somewhat wordy version) with a `requires` clause.

Received on 2022-05-27 14:16:12