Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple names for the same variable in C++

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

To achieve the same effect as this pseudocode

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 right semantics except it allocates space in the struct for the 3 references:

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 compile-time name substitution without increasing the size of the struct?

like image 369
wjd Avatar asked Dec 29 '11 23:12

wjd


2 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]; }
};
like image 101
Ben Voigt Avatar answered Oct 02 '22 05:10

Ben Voigt


I am not sure that you want to use inheritance in this case. You might be better of with a plain old union type:

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 );
like image 25
David Rodríguez - dribeas Avatar answered Oct 02 '22 06:10

David Rodríguez - dribeas