If I have a C++ union which contains an array. I would like to access each element of the array using a set of unique identifiers. (This may seem like a strange thing to want. In my application I have a union which contains pointers to cells in 8 directions, which represent how some object can move between cells. Sometimes it is convenient to write algorithms which work with indexes of arrays, however that is not convenient for an end user who would prefer to work with named identifiers rather than less obvious indices.)
Example:
union vector
{
double x;
double y;
double data[2];
}
I believe that x
and y
"are the same thing", so really one would have to:
struct v
{
double x, y;
}
union vector
{
v data_v_format;
double data_arr_format[2];
}
Which you then use:
vector v1;
v1.data_arr_format[0] = v1.data_v_format.y; // copy y component to x
Unfortunately this adds an ugly layer of syntax to the union. Is there any way to accomplish the original task as specified by the syntax:
union vector
{
double x;
double y;
double data[2];
}
Where x
is equivalent to data[0]
and y
is equivalent to data[1]
?
I could write a class to do this, where the "logically named identifiers become functions, returning a single component of the array" - but is there a better way?