Re: class layout and dummy template parameter
Mycroft Holmes wrote:
Hi to all,
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?
To give an alternative view to Igor's, I think not.
e.g.
template <int N>
struct POD
{
double x;
int h;
char c;
};
POD<1>* p = new POD<1>;
POD<2>* q = reinterpret_cast< POD<2>* >(p);
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.
The two types are indeed layout compatible. However, that doesn't allow
you to reinterpret_cast between them, but only allows you to put them
together in a union and access the members through either struct.
Layout-compatible only gives a few weak guarantees. See also 3.10/15:
[quote]
If a program attempts to access the stored value of an object through an
lvalue of other than one of the following types the behavior is
undefined48):
? the dynamic type of the object,
? a cv-qualified version of the dynamic type of the object,
? a type that is the signed or unsigned type corresponding to the
dynamic type of the object,
? a type that is the signed or unsigned type corresponding to a
cv-qualified version of the dynamic type of the object,
? an aggregate or union type that includes one of the aforementioned
types among its members (including, recursively, a member of a
subaggregate or contained union),
? a type that is a (possibly cv-qualified) base class type of the
dynamic type of the object,
? a char or unsigned char type.
48) The intent of this list is to specify those circumstances in which
an object may or may not be aliased.
[/quote]
IOW, that reinterpret_cast breaks aliasing rules, and thus might well
lead to bugs with optimization. e.g.
void f(POD<1>* a, POD<2>* b)
{
//compiler can assume that a != b (unless both are null!)
}
Tom