/prelude/evil_casts.hpp
C++ Header | 16 lines | 10 code | 4 blank | 2 comment | 0 complexity | 9a383cad833cf3ea04d7247d154ae475 MD5 | raw file
1#ifndef EVIL_CASTS_HPP 2#define EVIL_CASTS_HPP 3 4// Consider some_evil_cast<char const *>("foo") . There are two possible interpretations for the result: either the array should decay into a pointer and be immediately returned, or the bytes making up the array are interpreted as the bytes making up the to-be-returned pointer. cast_dammit_cast does the former, while savage_cast does the latter. 5 6template <typename To, typename From> To savage_cast (From const & from) 7{ return (To const &) from; } 8 // Can even be used to check endianness: geordi << hex << savage_cast<uint32_t>("\xef\xbe\xad\xde")) 9 10template <typename To, typename From> To cast_dammit_cast (From const from) 11{ 12 From const & r = from; // from itself is not a reference because we want arrays to decay, so that cast_dammit_cast<char*>("oi") works properly. 13 return (To const &) r; 14} 15 16#endif // header guard