Suppose we have class template Wrapper
like this:
template <class T>
struct Wrapper { T wrapped; };
For what types is it safe to reinterpret_cast
between a Type
and a Wrapper<Type>
? None? Standard-layout? All?
Suppose we created an object of one of these (Type
and Wrapper<Type>
), and read and write this object through the other. Example (live on godbolt.org):
void F1() {
std::stringstream ss;
ss << "Hello";
reinterpret_cast<Wrapper<std::stringstream>&>(ss).wrapped << " world";
}
void F2() {
Wrapper<std::stringstream> ss;
ss.wrapped << "Hello";
reinterpret_cast<std::stringstream&>(ss) << " world";
}
Reading the comments of this answer this area seems to be not quite unequivocal in the standard. I think that all compilers would generate a code that works as expected (i.e. a value of one type can be cast to the other), but the standard may not currently guarantee this. If it doesn't, the question arises: Could the standard guarantee well defined behaviour with these casts, or is it not possible/impractical to guarantee anything in such a case?
Cause I am pretty sure, that these casts will actually work.