Hacker News new | ask | show | jobs
by vinkelhake 420 days ago
> It’s too bad you still can’t cast a char to a uint8_t though in a constexpr expression.

Uh, what? That has worked fine since the introduction of constexpr in C++11.

1 comments

Maybe they meant reinterpret_cast from/to char to u8, which in this case isn't possible in constexpr.
Why would you need to do that though if you can static_cast?
You can't static_cast in this case; https://godbolt.org/z/a1bMbPcaj
You can use `std::bit_cast` to do that in constexpr contexts.

    constexpr auto f(uint8_t *x) {
      return std::bit_cast<char *>(x);
    }
https://godbolt.org/z/K3f9b9GGs
No, you can't do that either: https://godbolt.org/z/vzdTMazx7 : error: '__builtin_bit_cast' is not a constant expression because 'char' is a pointer type

Here the `constexpr` keyword means the function might be called in a constant-evaluated context. f doesn't need to have all its statements be able to be evaluated in constexpr, only those which are actually used are. You need to explicitly instantiate a constexpr variable to test this.

cppreference is very clear* about this, regarding bit_cast: https://en.cppreference.com/w/cpp/numeric/bit_cast

Good catch. Its weird that it compiles without error as a consteval func.
Ah this was my case! Was trying to constexpr a uint8_t ptr to char * in a constexpr constructor for a string class.

Ah that’s what bitcast is for, neat!