工会中的通用结构

Ben*_*n H 0 c++ templates

我正在尝试制作一个通用的矢量类.虽然我可以这样做:

struct vector3 {
  union {
    struct {
      float x;
      float y;
      float z;
    };
    float v[3];
  };
};
Run Code Online (Sandbox Code Playgroud)

我不能做到这一点:

template<int N, typename S, typename T = double>
class vec {
    union {
        T data[N];
        S;
    };
};

struct XY { REAL x, y; };
typedef vec<2, XY, REAL> Vector2;
Run Code Online (Sandbox Code Playgroud)

因为"S没有宣布任何东西."

有没有办法将通用模板参数作为联合的成员插入?基本上,我想将xy字段"注入" vec类.有没有更好的方法呢?

Jos*_*shD 6

您需要为该成员命名:

template<int N, typename S, typename T = double>
class vec {
    union {
        T data[N];
        S you_need_to_have_a_member_name_here;
    };
};

struct XY { REAL x, y; };
typedef vec<2, XY, REAL> Vector2;
Run Code Online (Sandbox Code Playgroud)

但更重要的是,你到底想要完成什么?如果你想要一个异构容器,你应该通过多态来实现.如果您想要通用矢量,请使用std::vector.

此外,您不能使用模板来提供成员名称,只能使用成员类型.上面提到的内容仍将被访问为Vector2::you_need_to_have_a_member_name_here.xVector2::you_need_to_have_a_member_name_here.y.

EDIT1

好的,你正在做的事情并不是那么简单.但是有一种简单的方法(虽然这是纯粹的邪恶).

#define Vec(D, X) struct Vector ## D { \
  X;  \
};

Vec(2, int x, y)
Vec(3, int x, y, z)
Vec(4, int w, x, y, z)
Vec(5, int v, w, x, y, z)
Run Code Online (Sandbox Code Playgroud)

它不漂亮,安全或理智,但它会起作用.仅当您确实需要特定的成员名称时才会这样.一般而言,如果您可以放弃该要求,则有更安全的方法.