0

everyone. We have a problem In the past, we have designed some mathematics classes used in graphics in VS2008 Using union to implement data synonyms, for example

class CMatrix4FLOAT {
public:
    union{
        struct { float m_Buffer[16];    };
        struct { float _M00, _M10, _M20, _M30,
                       _M01, _M11, _M21, _M31,
                       _M02, _M12, _M22, _M32,
                       _M03, _M13, _M23, _M33;  };
    }
    ...
    ...
};

Or

class CVectorReference4FLOAT {
public:
    union{
        struct { float &m_x, &m_y, &m_z, &m_w; };
        struct { float &m_s, &m_t, &m_p, &m_q; };
        struct { float &m_r, &m_g, &m_b, &m_a; };
    }
    ....
    CVectorReference4FLOAT(float * Array):
    m_x(Array[0]), m_y(Array[1]), m_z(Array[2]), m_z(Array[3]),
    m_s(Array[0]), m_t(Array[1]), m_p(Array[2]), m_q(Array[3]),
    m_r(Array[0]), m_g(Array[1]), m_b(Array[2]), m_a(Array[3])
    {}        
};

ex:
float Buffer[4];
CVectorReference4FLOAT P0(Buffer);
P0.m_x = 3.5f;
CVectorReference4FLOAT Color(Buffer);
Color.m_r = 0.7f;
CMatrix4f MatrixLookAt;
CVectorReference3FLOAT AxisX = MatrixLookAt.GetColumnVector(0); 

However, we are not allowed to use references in union after vs2015, which causes us some problems. We cannot use different names to represent the same data, or we need to take a little risk to change back to using point?

timrau
  • 22,578
  • 4
  • 51
  • 64
CROMA
  • 1
  • 1
  • Using a non-active union member is UB. What's your question? – super May 06 '20 at 06:25
  • A reference *must* be initialized, you can't assign to a reference (assigning to a reference assigns to the object being referenced). That's why you can't have references in unions like you show. This seems to be a problem in the original design and implementation, and I'm sorry to say that you might need to do some major refactoring or even redesign of your application. – Some programmer dude May 06 '20 at 06:26
  • Hi~ Reference can be initialized in preconstructor. It works in VS2008. – CROMA May 06 '20 at 09:07
  • Does this answer your question? [Use of Union with reference](https://stackoverflow.com/questions/38691282/use-of-union-with-reference) – Fausto Carvalho Marques Silva May 06 '20 at 09:48
  • Yes you can initialize the reference of *one* structure in the union, but what about the other structures? You might want to consider using a structure to wrap the whole union instead, and then make an instance of this structure instead. Then you could easily create references to the wrapper structure easily. – Some programmer dude May 06 '20 at 10:40

0 Answers0