Skip to content

Commit ad8a90a

Browse files
authored
Merge pull request #45166 from fwyzard/update_edm_bit_cast
Update `edm::bit_cast`
2 parents ab23b8e + c619df6 commit ad8a90a

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

FWCore/Utilities/interface/bit_cast.h

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,43 @@
1818
// Created: Wed, 01 Sep 2021 19:11:41 GMT
1919
//
2020

21+
// for compilers that do not support __has_builtin
22+
#ifndef __has_builtin
23+
#define __has_builtin(x) 0
24+
#endif
25+
2126
// system include files
2227
#include <cstring>
28+
#include <type_traits>
29+
30+
#if __cplusplus >= 202002L
31+
32+
// in C++20 we can use std::bit_cast
33+
34+
#include <bit>
35+
36+
namespace edm {
37+
using std::bit_cast;
38+
} // namespace edm
39+
40+
#elif __has_builtin(__builtin_bit_cast)
2341

24-
// user include files
42+
// before C++20 we can use __builtin_bit_cast, if supported
2543

2644
namespace edm {
27-
//in C++20 we can use std::bit_cast which is constexpr
28-
template <class To, class From>
29-
inline To bit_cast(const From &src) noexcept {
45+
template <typename To, typename From>
46+
constexpr inline To bit_cast(const From &src) noexcept {
47+
static_assert(std::is_trivially_copyable_v<From>);
48+
static_assert(std::is_trivially_copyable_v<To>);
3049
static_assert(sizeof(To) == sizeof(From), "incompatible types");
31-
To dst;
32-
std::memcpy(&dst, &src, sizeof(To));
33-
return dst;
50+
return __builtin_bit_cast(To, src);
3451
}
3552
} // namespace edm
36-
#endif
53+
54+
#else
55+
56+
#error constexpr edm::bit_cast is not supported by the compiler
57+
58+
#endif // __cplusplus >= 202002L
59+
60+
#endif // FWCore_Utilities_bit_cast_h

0 commit comments

Comments
 (0)