C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] Allow reinterpret_cast (and static_cast from void*) in a constant expression in limited cases
From: Brian Bi (bbi5291_at_[hidden])
Date: 2019-10-31 10:04:20


On Thu, Oct 31, 2019 at 9:23 AM Arthur O'Dwyer via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Thu, Oct 31, 2019 at 10:14 AM connor horman via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> I propose to allow reinterpret_cast from pointer to integral, as well as
>> the no-op/identity reintepret_cast in constant expressions. This particular
>> version is useful in implementing hashcode algorithms at compile time, and
>> to my knowledge bit_cast does not work for pointer types at compile time.
>>
>
> I think this is a non-starter. Consider:
>
> // https://godbolt.org/z/Xd48ZV
> const int i = 42;
> constexpr int is_64_aligned(const int *p) {
> return reinterpret_cast<intptr_t>(p) % 64 == 0;
> }
> constexpr bool x = is_64_aligned(&i);
> int main(int argc, char **argv) {
> bool y = is_64_aligned(argc ? &i : nullptr);
> assert(x == y);
> }
>
> How is the compiler supposed to know *at compile time* what bits are in
> the runtime bit-pattern of `p`?
>

Calling a constexpr function is not guaranteed to yield a constant
expression. That being said, I agree with your point. I can't think of
*any* case
where reinterpret_cast from pointer to integer could be forced to yield a
constant expression, except perhaps in the case of a null pointer (and even
then, the integral value would be implementation-defined---it might not be
0).

As for static_cast from void* to T* in constant expressions, it seems like
it should be allowed, but I think it was mentioned at some point that this
would be difficult to implement in current compilers, but I can't find the
thread. Hopefully someone else will chime in

>
> -Arthur
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

-- 
*Brian Bi*


STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups