1

I use Visual Studio, and I've noticed that there's no support for unrestricted unions. I've vritten a vec4 structure, basicly this:

template<class T>
struct vec4
{
    T x, y, z, w;

    vec4() :x(0), y(0), z(0), w(0) {}
    vec4(T x, T y, T z, T w) :x(x), y(y), z(z), w(w) {}
    vec4(const vec4& v) :x(v.x), y(v.y), z(v.z), w(v.w) {}
};

So the point is that I don't want to write vec2i (integer) vec2d (double) ect... separately. Then I made a 4 by 4 matrix:

template<class T>
struct mat4
{
    T elements[16];

    mat4()
    {
        for (int i = 0; i < 4 * 4; i++)
        {
            elements[i] = 0;
        }
    }
};

Again, the point is that I don't want to write all the separate types. I want to access the matrix columns as vec4s. But if I do this:

union
{
    T elements[16];
    vec4<T> columns[4];
};

I get C2621. As far as I know I can do this in GCC however I would like to avoid switching my development environment. Is there a workaround for this?

Edit: I've tried tricks like this:

vec4<T> * column(int col)
{
    return ((vec4<T>*) (((vec4<T>*)elements) + (sizeof(vec4<T>) * col)));
}

However this seems to give me a bad result.

CodezMe
  • 81
  • 1
  • 2
  • 9
  • Confirmed that it does compile in Clang: http://coliru.stacked-crooked.com/a/9576044d6bcbb3da and G++: http://coliru.stacked-crooked.com/a/0bb6d6d3e0dea217 – Mooing Duck Apr 06 '15 at 17:41
  • workaround would be `boost::variant`, which you should pretty much always use anyway. Unfortunately, it won't work for you, because what you're using unions for here is undefined behavior. – Mooing Duck Apr 06 '15 at 17:43

1 Answers1

1

https://msdn.microsoft.com/en-us/library/bd149yt8.aspx?f=255&MSPPError=-2147217396

Union member has a non-trivial copy constructor

An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects.

what about revmoving the copy ctor in "struct vec4" ?

Community
  • 1
  • 1
shawn
  • 4,305
  • 1
  • 17
  • 25
  • Pretty sure he has to remove _all_ the constructors. – Mooing Duck Apr 06 '15 at 17:38
  • Even if I remove the constructors, I error C2621: 'mat4::columns' : illegal union member; type 'vec4' has a copy constructor – CodezMe Apr 06 '15 at 17:42
  • strange, I read the reference http://en.cppreference.com/w/cpp/language/copy_constructor again and think that the code(without ctor) follows the reference, but vs2013 doesn't work. maybe it's another bug of vs2013? – shawn Apr 06 '15 at 18:17
  • My final solution was to fiddle with memory – CodezMe Apr 07 '15 at 16:25