Created
April 1, 2018 19:32
-
-
Save Nexuapex/477bed31e44b6a6c3642824f1788125f to your computer and use it in GitHub Desktop.
Minimal-dependencies implementation of bit_cast.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#if defined(__has_attribute) | |
#if __has_attribute(always_inline) | |
#define ALWAYS_INLINE __attribute__((always_inline)) | |
#endif | |
#endif | |
#if defined(_MSC_VER) | |
// To reduce debug build overhead: | |
// Enable intrinsic memcpy: /Oi | |
// Enable force-inlining: /Ob1 | |
#define ALWAYS_INLINE __forceinline | |
#endif | |
template <typename Dest, typename Source> | |
ALWAYS_INLINE Dest bit_cast(const Source& source) | |
{ | |
static_assert(sizeof(Dest) == sizeof(Source), "bit_cast to type of a different size"); | |
static_assert(__has_trivial_copy(Dest), "bit_cast to a type which is not trivially copyable"); | |
static_assert(__has_trivial_copy(Source), "bit_cast from a type which is not trivially copyable"); | |
// Note: could avoid calling constructor/destructor for Dest type, which is | |
// what this proposed implementation (for C++20 standardization) does: | |
// https://github.com/jfbastien/bit_cast/blob/master/bit_cast.h | |
Dest dest; | |
memcpy(&dest, &source, sizeof(dest)); | |
return dest; | |
} | |
// Example: | |
// https://godbolt.org/g/oqFZFH |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment