C ++ - Is there a way to create an alias for a field

Is there a way to create an alias for the / stuct class filed in C ++ 11? What I mean

I have a class

class Vector4
{
    public:
        float X,Y,Z,W;
}

I have an alias

typedef Vector4 Color;

Is there a way to create aliases for Vector4 X, Y, Z, W fields to work like the color R, G, B, A?

+4
source share
3 answers

Just define Vector4 like this using anonymous joins (without anonymous structures, although they are a common extension).

typedef struct Vector4
{
    union{float X; float R;};
    union{float Y; float G;};
    union{float Z; float B;};
    union{float W; float A;};
} Vector4;
typedef Vector4 Color;

Vector4, reinterpret_cast.
, , , .

struct Color
{
    float R, G, B, A;
}

:

- , :
- ( ) ,
- (10.3) (10.1),
- ( 11) ,
- ,
- ,
- , .

- , .
- , .

+4

alias - :

template <class Base, class Type, Type Base::*field>
struct Field {
   operator Type () const { return  base->*field; }
   Field& operator = (const Type& v) { base->*field = v; return *this; }

   Base* base;
};

, Color :

class Color {
   Vector4 v;
public:
   Color() : v{}, R{&v}, G{&v}, B{&v}, A{&v} {}
   Field<Vector4, float, &Vector4::X> R;
   Field<Vector4, float, &Vector4::Y> G;
   Field<Vector4, float, &Vector4::Z> B;
   Field<Vector4, float, &Vector4::W> A;
};

, Color Vector4...

+2

.

class Vector4
{
    public:

        Vector4 : X(0), Y(0), Z(0), W(1), R(X), G(Y), B(Z), A(W) {}

        float X,Y,Z,W;
        float& R;
        float& G;
        float& B;
        float& A;
};

, .

-.

class Vector4
{
    public:

        Vector4 : X(0), Y(0), Z(0), W(1){}

        float X,Y,Z,W;
        float& R() { return X ;}
        float& G() { return y ;}
        float& B() { return z ;}
        float& A() { return w ;}

        float const& R() const { return X ;}
        float const& G() const { return y ;}
        float const& B() const { return z ;}
        float const& A() const { return w ;}
};
+1

Source: https://habr.com/ru/post/1537237/


All Articles