Search code examples
c++constexprreinterpret-cast

reinterpret_cast fails constexpr function


Trying to create a constexpr capable class that reinterprets the bits of an IEEE double. Example:

constexpr double pi = 3.14159265358979323846;
constexpr fixedpoint a(pi);

However, running into the problem that reinterpret_cast is not a constant subexpression.

I am using this in the constexpr fixedpoint& operator=(double rhs) :

  uint64_t fraction = *reinterpret_cast<const uint64_t*>(&rhs) & 0x000F'FFFF'FFFF'FFFFull;

but the compiler flags that statement as a non-constant subexpression.

Tried type punning but that ran into the constraint that in C++ only a single field can be active.

Any one have a solution that allows me to reinterpret the bits of that double that is valid constexpr code?


Solution

  • Yes, use std::bit_cast, which is in header <bit>:

    #include <bit>
    #include <cstdint>
    constexpr double pi = 3.14159265358979323846;
    constexpr auto fraction = std::bit_cast<std::uint64_t>(pi) & 0x000F'FFFF'FFFF'FFFFull;
    

    You'll need a compiler with C++20 support. Currently there aren't any, but from Clang 9 you can at least use the builtin that will be used to implement bit_cast in future:

    #if __clang__
    constexpr auto fraction = __builtin_bit_cast(std::uint64_t, pi) & 0x000F'FFFF'FFFF'FFFFull;
    #endif
    

    Example.