Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
Ravenwater Avatar asked May 11 '26 17:05

Ravenwater


1 Answers

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.

like image 189
ecatmur Avatar answered May 14 '26 07:05

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!