Last active
July 16, 2018 13:40
-
-
Save mbitsnbites/fdfea67c1ff35960c1e33f724119faa6 to your computer and use it in GitHub Desktop.
raw_cast<T>() - C++ type punning
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 <cstring> | |
template <typename T2, typename T1> | |
inline T2 raw_cast(const T1& x) { | |
static_assert(sizeof(T2) == sizeof(T1), "raw_cast type sizes must match"); | |
T2 result; | |
std::memcpy(static_cast<void*>(&result), static_cast<const void*>(&x), sizeof(T2)); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment