0

クラスを考えてみましょう:

template<typename Type>
class CVector2
{
public:
    union {
        struct { Type x; Type y; };
        Type v[2];
    };

       // A bunch of methods for vector manipulation follow
}

次のように使用できます。

CVector2<int> vec;
vec.x = 1;
vec.y = rand();
// ...
vec.v[rand() & 1] = vec.x;

問題は、構造体に名前が付けられていないため、この共用体が標準 C++ ではないことです。標準にする方法は1つしかありません-構造に名前を付けます:

union {
        struct { Type x; Type y; } xy;
        Type v[2];
      };

次に、ベクター フィールドへのアクセスを長くする必要があります。

CVector2<int> vec;
vec.xy.x = 1;
vec.xy.y = rand();
// ...
vec.v[rand() & 1] = vec.xy.x;

または、便利なメソッドを宣言する必要がありますが、これは役に立ちますが、複雑なユースケースでは余分な波括弧のためにアクセスが面倒になる可能性があります。

class CVector2
{
public:
    union {
        struct { Type x; Type y; };
        Type v[2];
    };

    Type& x() {return xy.x;}
    const Type& x() const {return xy.x;}
    Type& y() {return xy.y;}
    const Type& y() const {return xy.y;}
}

使用例:

void setGeometry (CVector2<int> p1, CVector2<int> p2)
{
   setGeometry(CRect(CPoint(p1.x(), p1.y()), CPoint(p2.x(), p2.y())));
}

不足している -pedantic-errors で CVector2 クラスをコンパイルするより良い方法はありますか?

4

1 に答える 1