<分区>
考虑以下结构:
struct vec4
{
union{float x; float r; float s};
union{float y; float g; float t};
union{float z; float b; float p};
union{float w; float a; float q};
};
类似这样的东西似乎被用在了例如GLM提供类似 GLSL 的类型,如 vec4
、vec2
等。
但是尽管预期的用途是使这成为可能
vec4 a(1,2,4,7);
a.x=7;
a.b=a.r;
,这似乎是一个未定义的行为,因为,如引用 here ,
In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time.
例如,不是更好吗?只需定义如下所示的结构?
struct vec4
{
float x,y,z,w;
float &r,&g,&b,&a;
float &s,&t,&p,&q;
vec4(float X,float Y,float Z,float W)
:x(X),y(Y),z(Z),w(W),
r(x),g(y),b(z),a(w),
s(x),t(y),p(z),q(w)
{}
vec4()
:r(x),g(y),b(z),a(w),
s(x),t(y),p(z),q(w)
{}
vec4(const vec4& rhs)
:x(rhs.x),y(rhs.y),z(rhs.z),w(rhs.w),
r(x),g(y),b(z),a(w),
s(x),t(y),p(z),q(w)
{}
vec4& operator=(const vec4& rhs)
{
x=rhs.x;
y=rhs.y;
z=rhs.z;
w=rhs.w;
return *this;
}
};
或者我是在解决一个不存在的问题?是否有一些特殊的声明允许访问相同类型的非事件 union 成员?