Hack of the day: Array-like access to fields
February 26, 2011
Sometimes it is useful if you are able to access fields of a struct or class as an array.
For example, if you have the following struct:
struct Point3D {
float x,y,z;
};
but you require to access the x,y and z-fields as an array, you can use an union:
union Point3D {
float coord[3];
struct {
float x,y,z;
};
};
Point3D p;
p.x = 1;
p.coord[1] = 2; // the same as p.y = 2;
p.z = 3;
Another possibility is to create a class and overload the []-operator:
class Point3D {
public:
float& operator[](int x) {
assert(x <= 2 && x >= 0);
if (x == 0) return this->x;
if (x == 1) return this->y;
return this->z;
}
float x,y,z;
};
Point3D p;
p.x = 1;
p[1] = 2;
p.z = 3;
I don’t like these ifs in the operator[]
The operator[] itself is nice, but there is another way – the one that is used in D3DX in structs like D3DXVECTOR3:operator float * () { return &x; }operator const float * () const { return &x; }
wow, very nice one. thank you for the tip. i love it
# float& operator[](int i) { # assert(i = 0); # return (&x)[i]; # }