Allied hack needed

I have a structure representing the top. It has fields x, y and z, as well as several others. Recently, I came to the conclusion that for certain functionality I will need to access the coordinates of the vertices in the form of an array. I did not want to "pollute" the code with temporary variables or change all places that look like vy to this v.coord[1] , which is neither cute nor elegant. So I thought about using union. Something like this should work:

 struct { float x,y,z; } Point; struct { union { float coord[3]; Point p; }; } Vertex; 

This is good, but not perfect. A point class does not make sense. I want to have access to the y coordinate just by typing vy (not vpy ).
Can you suggest hacking this solution (or say that this is impossible)?

+6
c ++ c
source share
2 answers

A good C ++ approach is to use named accessors that return links to elements:

 class Point { public: float& operator[](int x) { assert(x <= 2); return coords_[x]; } float operator[](int x) const { assert(x <= 2); return coords_[x]; } float& X() { return coords_[0]; } float X() const { return coords_[0]; } float& Y() { return coords_[1]; } float Y() const { return coords_[1]; } float& Z() { return coords_[2]; } float Z() const { return coords_[2]; } private: float coords_[3]; }; 

With this approach, given Point p; , you can use both p[0] and pX() to access the source element of the coords_ internal array.

+14
source share

Ok this should work for you

 struct { union { float coord[3]; struct { float x,y,z; }; }; } Vertex; 

What this code does is that it combines an array with a structure, so they use the same memory. Since the structure does not contain a name, it is available without a name, as is the union itself.

+12
source share

All Articles