]>
Commit | Line | Data |
---|---|---|
1e59de90 TL |
1 | #pragma once |
2 | ||
3 | #include <cstring> | |
4 | #include <type_traits> | |
5 | ||
6 | namespace std { | |
7 | ||
8 | #ifndef __cpp_lib_bit_cast | |
9 | #define __cpp_lib_bit_cast 201806L | |
10 | ||
11 | /// Create a value of type `To` from the bits of `from`. | |
12 | template<typename To, typename From> | |
13 | requires (sizeof(To) == sizeof(From)) && | |
14 | std::is_trivially_copyable_v<From> && | |
15 | std::is_trivially_copyable_v<To> | |
16 | [[nodiscard]] constexpr To | |
17 | bit_cast(const From& from) noexcept { | |
18 | #if __has_builtin(__builtin_bit_cast) | |
19 | return __builtin_bit_cast(To, from); | |
20 | #else | |
21 | static_assert(std::is_trivially_constructible_v<To>); | |
22 | To to; | |
23 | std::memcpy(&to, &from, sizeof(To)); | |
24 | return to; | |
25 | #endif | |
26 | } | |
27 | ||
28 | #endif // __cpp_lib_bit_cast | |
29 | ||
30 | } // namespace std |