C++ union array and vars?

2019-04-26 10:36发布

问题:

There's no way to do something like this, in C++ is there?

union {
    {
        Scalar x, y;
    }
    Scalar v[2];
};

Where x == v[0] and y == v[1]?

回答1:

How about

union {
    struct {
        int x;
        int y;
    };
    int v[2];
};

edit:

union a {
    struct b { int first, second; } bee;
    int v[2];
};

Ugly, but that's more accurate



回答2:

Since you are using C++ and not C, and since they are of the same types, why not just make x a reference to v[0] and y a reference to v[1]



回答3:

Try this:

template<class T>
struct U1
{
    U1();
    T   v[2];
    T&  x;
    T&  y;
};

template<class T>
U1<T>::U1()
    :x(v[0])
    ,y(v[1])
{}

int main()
{
    U1<int>   data;

    data.x  = 1;
    data.y  = 2;
}


回答4:

I've used something like this before. I'm not sure its 100% OK by the standard, but it seems to be OK with any compilers I've needed to use it on.

struct Vec2
{
  float x;
  float y;
  float& operator[](int i) { return *(&x+i); }
};

You can add bounds checking etc to operator[] if you want ( you probably should want) and you can provide a const version of operator[] too.



回答5:

Depending on what "Scalar" is, yes, you can do that in C++. The syntax is almost exactly (maybe even exactly exactly, but I'm rusty on unions) what you wrote in your example. It's the same as C, except there are restrictions on the types that can be in the unions (IIRC they must have a default constructor). Here's the relevant Wikipedia article.



标签: c++ unions