0

Reading thru https://github.com/isocpp/CppCoreGuidelines/issues/1517 I got the idea to get rid of the non-constexpr reinterpret_cast from my µC code (e.g. C could be a µC internal peripheral on address 0x100). Therefore I tried std::bit_cast-ing to a pointer type.

struct C {
    inline static constexpr uintptr_t address = 0x100;
    inline static constexpr C* ptr1 = std::bit_cast<C*>(address);
    inline static /*constexpr*/ C* ptr2 = reinterpret_cast<C*>(address);
};

But according to the standard this is not possible because in this case std::bit_cast is not allowed to be constexpr (like reinterpret_cast).

Looks like this is still not possible? But why?

wimalopaan
  • 4,838
  • 1
  • 21
  • 39
  • These are the answers you might seek: https://en.cppreference.com/w/cpp/numeric/bit_cast#Notes https://en.cppreference.com/w/cpp/language/reinterpret_cast#Type_aliasing Mainly due to the possibility of Undefined Behavior. It is marked ``constexpr`` but the implementation wouldn't able to evaluate it to a constant. – SimplyCode Oct 31 '22 at 16:40
  • 1
    `std::bit_cast` with pointer types is exactly the same as `reinterpret_cast`, so the rules for why that isn't allowed in a constant expression are the same reasons why you can't use `bit_cast`. – NathanOliver Oct 31 '22 at 16:41

0 Answers0