I'm learning C++ and reading Andrei Alexandrescu's book on generic programming. He presents a templated class that can be used to convert between types:
template <class To, class From>
To safe_reinterpret_cast(From from)
{
assert(sizeof(From) <= sizeof(To));
return reinterpret_cast<To>(from);
}
This works fine for:
int i = 5;
char* p = safe_reinterpret_cast<char*>(i);
but fails for
std::string a("apple");
char* pp = safe_reinterpret_cast<char*>(a);
This is the error failure at compile time:
invalid cast from type 'std::basic_string<char>' to type 'char*'
Why does this cast fail?
Andrei Alexandrescu's infamous example only works for plain-old-data types.
It does not work for pointers. The behaviour of casting unrelated pointer types is undefined.
You can only reinterpret_cast to void*
, and reinterpret_cast from void*
back to the original pointer type.