1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the point here is that std::string is not a pointer, nor a POD.
1

Because int and char are primitive types, while std::string is not.

1 Comment

so my larger question is can reinterpret_cast never be used for non-primitive types?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.