J
JKop
You know how from time to time, you want to have an array which you can
access via:
array_name[element];
But also, you'd like the more user-friendly option:
array_name.element1
array_name.element2
I believe that some people use a union with an anonymous struct for this
(which is not legal Standard C++) as follows:
union Week
{
unsigned days[7];
struct
{
unsigned monday;
unsigned tuesday;
... //and so on
};
} christmas_week;
Well firstly, even if anonymous structs *were* legal, the above code would
still not necessarily work as expected - to be specific, "tuesday" doesn't
necessarily have the same address as days[1], and why? padding.
So... the following is my way of doing it. The only drawback is that it's no
longer an aggreagate nor a POD:
struct Week
{
unsigned days[7];
unsigned &monday;
unsigned &tuesday;
... //and so on
Week() : monday( days[0] ), tuesday( days[1] ) //and so on
};
-JKop
access via:
array_name[element];
But also, you'd like the more user-friendly option:
array_name.element1
array_name.element2
I believe that some people use a union with an anonymous struct for this
(which is not legal Standard C++) as follows:
union Week
{
unsigned days[7];
struct
{
unsigned monday;
unsigned tuesday;
... //and so on
};
} christmas_week;
Well firstly, even if anonymous structs *were* legal, the above code would
still not necessarily work as expected - to be specific, "tuesday" doesn't
necessarily have the same address as days[1], and why? padding.
So... the following is my way of doing it. The only drawback is that it's no
longer an aggreagate nor a POD:
struct Week
{
unsigned days[7];
unsigned &monday;
unsigned &tuesday;
... //and so on
Week() : monday( days[0] ), tuesday( days[1] ) //and so on
};
-JKop