struct vec2
{
union
{
struct { float x, y; };
struct { float r, g; };
struct { float s, t; };
};
vec2() {}
vec2(float a, float b) : x(a), y(b) {}
};
struct vec3
{
union
{
struct { float x, y, z; };
struct { float r, g, b; };
struct { float s, t, p; };
// Here is the problem with g++.
struct { vec2 xy; float z; };
struct { float x; vec2 yz; };
};
vec3() {}
vec3(float a, float b, float c) : x(a), y(b), z(c) {}
};
The code above compiles and works as expected in Visual Studio and so I can use it like
vec3 v1(1.f, 2.f, 3.f);
vec2 v2 = v1.yz; // (2, 3)
Not in g++ (MinGW).
src/main.cpp:22:23: error: member 'vec2 vec3::<unnamed union>::<unnamed struct>::xy' with constructor not allowed in anonymous aggregate
src/main.cpp:22:33: error: redeclaration of 'float vec3::<unnamed union>::<unnamed struct>::z'
src/main.cpp:18:30: note: previous declaration 'float vec3::<unnamed union>::<unnamed struct>::z'
src/main.cpp:23:32: error: member 'vec2 vec3::<unnamed union>::<unnamed struct>::yz' with constructor not allowed in anonymous aggregate
src/main.cpp:23:24: error: redeclaration of 'float vec3::<unnamed union>::<unnamed struct>::x'
src/main.cpp:18:24: note: previous declaration 'float vec3::<unnamed union>::<unnamed struct>::x'
I think I shouldn't be doing it like that in the first place. Any Ideas?
Edit: After reading a lot of articles and exploring open-source projects, I started to get how vector swizzling should be like and posted the solution below, still waiting for better answers though.
Edit 2: All
vec*
members must be accessed only from the parent like the GLM library.