有没有办法构造一个 constexpr 函数来获取双精度的位表示

Is there a way to construct a constexpr function to get bit representation of a double?

本文关键字:函数 constexpr 获取 双精度 表示 一个 有没有      更新时间:2023-10-16

有没有一种标准方法来构造一个允许将双精度转换为 64 位表示的 constexpr 函数:

constexpr uint64_t double_to_uint64_t(double d) {
   ??????
}

因此

constexpr uint64_t two_bits = double_to_uint64_t(2.0);

会编译吗?

反向方法(uint64 到双倍(也很有趣。

直到C++20。所有常见的技巧要么是完全禁止的(reinterpret_cast(,要么是未定义的行为,UB在编译时执行时会变得格式不正确。

C++20 提供了 std::bit_cast ,它在两种类型之间进行二进制转换,只要它们都是可复制的并且具有相同的大小。并且该函数是constexpr的,因此您可以在编译时使用它。