Re: union float[3] and x,y,z
Erik Wikstr?m wrote:
On 2007-09-25 14:26, Gernot Frisch wrote:
Uhm...
Is there any way of making
float pos[3];
a union of
float x,y,z;
somehow, so I can use:
mything[0] = mything.y;
instead of mything.x = mything.y
No, however you can do something like this:
struct thing
{
float arr[3];
float& x;
float& y;
float& z;
thing() : x(arr[0]), y(arr[1]), z(arr[2]) {}
};
Which allows you to access x through either t.x or through t.arr[0]
where t is an object of type thing:
int main()
{
thing t;
t.x = 1;
t.y = 2;
t.arr[2] = 3;
int i = 0;
}
If you want to be able to use t[0] instead of t.arr[0] you have to
overload the [] operator as Alexander Dong Back Kim suggested.
Actually, could still do that if you do this trick:
struct thing {
float x, y, z;
struct thing_indexing {
thing& t;
thing_indexing(thing& t) : t(t) {}
float& operator[](int i) {
return i < 2 ? i < 1 ? t.x : t.y : t.z;
}
} arr;
thing() : arr(*this) {}
thing& operator=(thing const& t) {
x = t.x;
y = t.y;
z = t.z;
}
};
int main() {
thing t;
t.x = 3.1415926;
t.arr[1] = t.x;
}
RATS! I got pulled in and am writing code when I didn't want to....
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask