C++ union array and vars?

2019-04-26 10:31发布

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]?

标签: c++ unions
5条回答
一夜七次
2楼-- · 2019-04-26 11:18

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.

查看更多
祖国的老花朵
3楼-- · 2019-04-26 11:25

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

查看更多
时光不老,我们不散
4楼-- · 2019-04-26 11:26

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.

查看更多
\"骚年 ilove
5楼-- · 2019-04-26 11:30

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]

查看更多
Bombasti
6楼-- · 2019-04-26 11:32

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;
}
查看更多
登录 后发表回答