Created
November 14, 2016 09:04
-
-
Save remyroez/215f3d321abb175a8260f1cd39fb346b to your computer and use it in GitHub Desktop.
Force cast
This file contains hidden or 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 <iostream> | |
template <typename T, typename U> | |
constexpr inline T &force_cast(U &u) { return (*reinterpret_cast<T *>(&u)); } | |
template <typename T, typename U> | |
constexpr inline const T &force_cast(const U &u) { return (*reinterpret_cast<const T *>(&u)); } | |
struct foo { int value = 123; }; | |
int main() | |
{ | |
auto a = 1.23f; | |
auto b = force_cast<int>(a); | |
auto c = force_cast<decltype(a)>(b); | |
auto d = force_cast<foo>(456); | |
std::cout << a << std::endl; | |
std::cout << b << std::endl; | |
std::cout << c << std::endl; | |
std::cout << d.value << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment