Re: class layout and dummy template parameter
"Mycroft Holmes" <m.holmes@nospam.it> wrote in message
news:OG$lGWtEHHA.3660@TK2MSFTNGP06.phx.gbl
suppose I have a POD, whose type is actually a template with a DUMMY
parameter.
Is there any *guarantee* that I can reinterpret_cast the object to a
different instantiation of the same template?
e.g.
template <int N>
struct POD
{
double x;
int h;
char c;
};
Yes, there is such a guarantee. All specializations of POD template are
layout-compatible, you are allowed to cast between them.
I think this code is valid and covered by the paragraphs on the
"layout compatibility" between POD-structs, but I don't have a copy
of the standard here. Any hint is appreciated.
If you need chapter and verse, here goes:
3.9/11 If two types T1 and T2 are the same type, then T1 and T2 are
layout-compatible types.
9.2/14 Two POD-struct (clause 9) types are layout-compatible if they
have the same number of members, and corresponding members (in order)
have layout-compatible types.
9.2/17 A pointer to a POD-struct object, suitably converted using a
reinterpret_cast, points to its initial member (or if that member is a
bitfield, then to the unit in which it resides) and vice versa.
So strictly speaking, by the letter of the standard, you are guaranteed
that the following is safe:
POD<1>* p = new POD<1>;
double* px = reinterpret_cast<double*>(p);
POD<2>* q = reinterpret_cast< POD<2>* >(px);
I believe it is safe to roll two casts into one, but the standard does
not appear to explicitly allow it.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925