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?