Multiple names for the same variable in C ++

Is it possible in C ++ to refer to the same variable using different names without using a preprocessor?

To achieve the same effect as this pseudo code

struct vec3f {
    float[3] values;
};

struct color : public vec3f {
    #define r values[0]
    #define g values[1]
    #define b values[2]
};

color c;
c.r = 0.5f;

The following has the correct semantics, except that it allocates space in the structure for three links:

struct color : public vec3f {
    float& r;
    float& g;
    float& b;
    color() : r(values[0]), g(values[1]), b(values[2]) { }
};

Is there a way to get this replacement of a compile-time name without increasing the size of the structure?

+5
source share
4 answers

How about this?

struct vec3f {
    float[3] values;
};

struct color : public vec3f
{
    float& r() { return values[0]; }
    float& g() { return values[1]; }
    float& b() { return values[2]; }
    const float& r() const { return values[0]; }
    const float& g() const { return values[1]; }
    const float& b() const { return values[2]; }
};
+9
source

I'm not sure if you want to use inheritance in this case. You might be better off with the plain old type union:

typedef float vec3f[3];
union color {
   vec3f values;
   struct {
      float r;
      float g;
      float b;
   };
};

color c;
c.values[0] = 10;
assert( c.r == 10 );
+2
source

1

, . .

struct vec3f
{
    float values[3];
};

struct tempvec
{
    float &r;
    float &g;
    float &b;

    tempvec( vec3f& bar )
        :r(bar.values[0]) 
        , g(bar.values[1]) 
        , b(bar.values[2]){}
};

int main() 
{
    vec3f temp;
    temp.values[0] = 2.40f;

    //when you want to alias values[0] as r do this
    tempvec(temp).r = 42;
    tempvec(temp).g = 42;

    return 0;    
}

2

, vec3f vec3c .. padding/alignment ..

struct vec3f
{
    float values[3];
};

struct vec3c
{
    float r,g,b;
};

int main() 
{
    vec3f temp;
    temp.values[0] = 2.40f;

    vec3c* alias  = reinterpret_cast<vec3c*>(&temp);

    alias->r = 4.2f;
    alias->g = 4.2f;
    alias->b = 4.2f;

    return 0;    
}
+1

, .

, , static const array-of-pointer-to-member. operator[] , -, this .

This works because pointers to elements are not ordinary pointers; they are a little more magical than that. (This allows you to create non-bound pointers to member functions and why they cannot be used where simple function pointers are expected).

It also means that you don’t need to use any casting tricks, rely on any kind of alignment, intolerable behavior of anonymous merging or guarantees of the layout of the memory, and you can still refer to the structure components as named fields and not through access functions.

+1
source

All Articles