C++ union array and vars?

前端 未结 8 1599
日久生厌
日久生厌 2021-02-19 22:18

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

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

Where x == v[0]<

8条回答
  •  心在旅途
    2021-02-19 22:42

    Given your example:

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

    As others have noted, in general, the standard does not guarantee that there will be no padding between x and y, and actually compilers inserting padding in structures is pretty common behavior.

    On the other hand, with solutions like:

    struct U
    {
        int   v[2];
        int&  x;
        int&  y;
    };
    
    U::U()
        : x(v[0])
        , y(v[1])
    {}
    

    what I don't like mainly is the fact that I have to mention x, y twice. For cases where I have more than just a few elements (say 10), this becomes much less readable and harder to maintain. Additionally U can no longer be a POD since it needs a user-defined constructor. And finally, the x & y references consume additional memory.

    Hence, the (acceptable for me) compromise I've come up with is:

    struct Point
    {
        enum CoordType
        {
            X,
            Y,
            COUNT
        };
    
        int coords[CoordType::COUNT];
    };
    
    typedef Point::CoordType PtCoord;
    

    With this you can then do:

    Point p;
    for ( int i = 0; i < PtCoord::COUNT; i++ )
        p.coords[i] = 100;
    std::cout << p.coords[PtCoord::X] << " " << p.coords[PtCoord::Y] << std::endl;
    
    // 100 100
    

    A bit sophisticated but I prefer this over the references suggestion.

提交回复
热议问题