"Simon Elliott" <Simon at ctsn.co.uk> wrote in message
news:41***********************@news.gradwell.net.. .
I'd like to do something along these lines:
struct foo
{
int i1_;
int i2_;
};
struct bar
{
double d1_;
double d2_;
};
typedef std::vector<foo> vectorFoo;
typedef std::vector<bar> vectorBar;
union vectorAll
{
vectorFoo foo_;
vectorBar bar_;
};
static vectorAll myVectorAll;
...
foo myFoo;
myVectorAll.foo_.push_back(myFoo);
myVectorAll.foo_.clear();
...
bar myBar;
myVectorAll.bar_.push_back(myBar);
myVectorAll.bar_.clear();
But a) I'm fairly sure that this isn't valid C++ because std::vector
must have a constructor,
It's invalid because std::vector *does* have a (non-trivial)
constructor (as well as other precluded member functions).
(C&V below)
b) it seems very unsafe.
Well, I suppose it you were able to convince a compiler
to create code for it, it would very likely be 'unsafe'. :-)
and c) it precludes
sensible requirements such as
Such as violating the standard's rules. :-)
clearing myVectorAll without knowing what
type is in it. (Intuitively one might want to be able to do a
myVectorAll.clear());
I wouldn't intiut that because the your union has no member
functions.
Given that one of my target compilers is too uncompliant to compile
boost, I can't use boost::any for this. What are my other options?
Don't use a union. :-) How about a function template?
(Of course that's just a guess, without knowing more
about what you're trying to do.)
ISO/IEC 14882:1998(E)
9.5 Unions
1 In a union, at most one of the data members can be active
at any time, that is, the value of at most one of the data
members can be stored in a union at any time. [Note: one
special guarantee is made in order to simplify the use of
unions: If a POD*-union contains several POD*-structs that
share a common initial sequence (9.2), and if an object of
this POD*-union type contains one of the POD*-structs, it is
permitted to inspect the common initial sequence of any of
POD*struct members; see 9.2. ] The size of a union is suffi*-
cient to contain the largest of its data members. Each data
member is allocated as if it were the sole member of a struct.
A union can have member functions (including constructors
and destructors), but not virtual (10.3) functions. A union
shall not have base classes. A union shall not be used as a
base class. An object of a class with a non*-trivial constructor
(12.1), a non-*trivial copy constructor (12.8), a non*-trivial
destructor (12.4), or a non-*trivial copy assignment operator
(13.5.3, 12.8) cannot be a member of a union, nor can an
array of such objects. If a union contains a static data
member, or a member of reference type, the program is ill-*formed.
-Mike