Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union hack needed

Tags:

c++

c

I have a struct that represents a vertex. It has x, y and z fields as well as several others. Recently I came into conclusion that for certain functionality I will need to access the coordinates of the vertex as an array. I didn't want to "pollute" the code with temporary variables or change all places that look like this v.y to this v.coord[1] which is not nice nor elegant. So I thought about using a 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. The point class has no point being there. I want to be able to access y coordinate simply by typing v.y (and not v.p.y).
Can you suggest a hack to solve this (or tell me that it is not possible)?

like image 976
Artium Avatar asked Dec 24 '10 19:12

Artium


2 Answers

A good C++ approach is to use named accessors that return references to the 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 a Point p;, you can use both p[0] and p.X() to access the initial element of the internal coords_ array.

like image 54
James McNellis Avatar answered Oct 19 '22 14:10

James McNellis


OK, this should work for you

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

What this code does is that it unions the array with the structure, so they share the same memory. Since the structure doesn't contain a name, it is accessible without a name, just like the union itself.

like image 27
Rafid Avatar answered Oct 19 '22 13:10

Rafid