Re: Proposal to allow unions of any data type
"skaller" <skaller@users.sourceforge.net> wrote in message
union X {
string a;
vector b;
X(): a("") {}
};
struct X
{
union
{ struct { string a; };
struct { vector b; };
};
X() { a=string(""); }
};
You can almost get what you want if we simply ratify the existence of
anonymous structs (as per MS VC6-8) - and given they must have default
constructors, are thus permitted as members of unions.
Of course, a lot of this friction simply comes down to people trying to
pretend the union is a class when it's actually a completely different
animal (an overlay).
It is not sensible for a union to have default construction, nor is it
sensible for it to have methods.
Create 'overlay'
An overlay is identical to an anonymous union except:
1) Overlays may only exist as members of classes
2) Overlays do not have any methods
3) Overlays are not constructed (though if static are memset zero) or
destroyed
4) Overlays with non-pod members require a user defined
constructor/destructor/copy-assign operator in the enclosing class
(otherwise memcpy is used)
5) Members can be accessed in any order, although if their state data is
read, behaviour is undefined unless it was initialised by a compatible
representation (including a derived class) (as per reinterpret_cast).
6) Overlays may have any kind of members with no restrictions
7) One overlay member may appear in the initialiser list of an enclosing
class's constructor
8) The members of an overlay may have access specifiers
So, your case would become:
struct X
{ overlay
{ string a;
vector b;
};
X():a("") { }
};
It is probably inadvisable to expose this overlay in this way (as it is
often inadvisable to expose member variables), unless string and vector are
compatible types.
Here's a better example for an exposed overlay:
struct A { float x,y,z; };
struct B: A
{ B& operator=(float f) { x=f; return *this; }
B(float f) { x=f; }
operator float() const { return x; }
};
struct V
{
overlay
{ protected: A a;
public: B x; // Same data as A, but different behaviour
};
...
};
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]