Solved
union initalization
Posted on 1999-01-22
Hello,
my problem is the following.
I want to allow the static initalization of a record array.
The record has one field supposed to be a union of different types.
It's structure is the following:
typedef struct {
char* name;
int type;
union {
int x;
char* str;
double flt;
} val;
} fieldRec;
fieldRec recordDef[] = {
{ "field1", intType, 3 },
{ "field2", strType, "a string" },
{ "filed3", fltType, 0.123456789 }
};
This is wraped inside of a macro but this is what is effectively written.
The problem is that static initalization of union can only be done with using the first type of the union.
Casting to the first type is not a good solution.
It may work with pointers on most computers but will fail with double since it does a conversion and not just a cast.
(I use -int64 under visual C++) The value given in the example will be converted to zero.
My objective is to provide an easy and intuitive way to define and initialize this field definition vector.
I want this initialization to be static because there are plenty of them.
Thus I would like to avoid constructors if possible and if it could be compatible with C, it would be the best solution.
Usage of a macro to wrap the field declaration is ok. Avoiding the need for the user to cast the given value would be allright.
Any suggestion ?
The points will be increased if the answers satisfies all requirements.