diff --git a/FWCore/Utilities/interface/bit_cast.h b/FWCore/Utilities/interface/bit_cast.h index d8301a7100b06..9db30538a9406 100644 --- a/FWCore/Utilities/interface/bit_cast.h +++ b/FWCore/Utilities/interface/bit_cast.h @@ -18,19 +18,43 @@ // Created: Wed, 01 Sep 2021 19:11:41 GMT // +// for compilers that do not support __has_builtin +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + // system include files #include +#include + +#if __cplusplus >= 202002L + +// in C++20 we can use std::bit_cast + +#include + +namespace edm { + using std::bit_cast; +} // namespace edm + +#elif __has_builtin(__builtin_bit_cast) -// user include files +// before C++20 we can use __builtin_bit_cast, if supported namespace edm { - //in C++20 we can use std::bit_cast which is constexpr - template - inline To bit_cast(const From &src) noexcept { + template + constexpr inline To bit_cast(const From &src) noexcept { + static_assert(std::is_trivially_copyable_v); + static_assert(std::is_trivially_copyable_v); static_assert(sizeof(To) == sizeof(From), "incompatible types"); - To dst; - std::memcpy(&dst, &src, sizeof(To)); - return dst; + return __builtin_bit_cast(To, src); } } // namespace edm -#endif + +#else + +#error constexpr edm::bit_cast is not supported by the compiler + +#endif // __cplusplus >= 202002L + +#endif // FWCore_Utilities_bit_cast_h