I'm sure many of you will have come across this situation before and am wondering the most elegant way of solving it:
This is an example, of wanting to create a struct/class that is an extension of a smaller version, and wanting to still be able to access the smaller version via a union. However the compiler seems to want the smaller struct to be a POD type (presumably because which constructors / destructors to call in a union is ambiguous). This is what I want, but it won't compile, complaining about Point2 being non-POD:
struct Point2
{
Point2() {} // want this to be default
Point2(int a, int b) {x = a; y = b;} // extra constructor for ease of use
int x, y;
};
struct Point3
{
union
{
struct
{
int x, y, z;
};
struct
{
Point2 xy; // access a Point3 as either a Point3 or a Point2
};
};
};
The only problem is it is sometimes very useful to be able to use the 2nd constructor when passing a Point2 as an argument to a function:
DrawLineTo(Point2(10, 20));
void DrawLineTo(const Point2 &pt)
{
...
}
I am understanding there has been some changes to POD types in later c++ (I now have c++11 available), so is there any way of keeping it as a POD type while still having the secondary constructor available?
I can also see alternative methods of doing the same kind of thing (perhaps not using a union). What do you guys use?
↧