c++ - 使 vector 3D 从 vector AND 派生,需要保留字段 x y z

标签 c++ inheritance field unions

我有一个 vector 3D 类

class Vector3D{
    public: float x; float y; float z;
    //some functions, e.g. operator+ - * / 
    //some 3D-specific function
};

和一个 vector N-D 类。

template<int constSize> class VecFloatFix{
    float database[constSize];
    //some functions, e.g. operator+ - * / 
};

我注意到两个类之间存在代码重复,所以我认为我应该制作 Vector3D源自 VecFloatFix<3> :-

class Vector3D : public VecFloatFix<3>{
    //some 3D-specific function
};

一切似乎都很好,除了有很多用户代码访问Vector3D::x,y,z直接。

是否可以制作Vector3D源自 VecFloatFix<3>同时不破坏用户的代码?

我最好的猜测是:-

template<int constSize> class VecFloatFix{
    union{
        float database[constSize];
        float x,y,z;  ?????  sound like a hack
    }
    //some functions, e.g. operator+ - * / 
};

编辑硬编码x,y,z进入VecFloatFix是不可持续的。
如果我有一个新类(class)Vector2D源自 VecFloatFix<2> , Vector2D::z将编译正常(危险)。

最佳答案

这里是一个版本,它只公开了大小为 3 的 vector 的 xyz 组件。显然其他大小也可以专门化.

template<int constSize> struct VecFloatStorage
{
    float database[constSize];
};

template<> struct VecFloatStorage<3>
{
    union
    {
        float database[3];
        struct { float x, y, z; };
    };
};

template<int constSize> class VecFloatFix : public VecFloatStorage<constSize>
{
public:
    // Methods go here.
};

不知道标准是否保证 struct { float x, y, z; } 具有与 float data[3] 相同的内存布局,但在实践中我非常确定该假设成立。

GLM 库使用了类似的技巧,除了它们根本没有数组成员,而是提供返回 (&this->x)[idx] 的索引运算符

关于c++ - 使 vector 3D 从 vector AND 派生,需要保留字段 x y z,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885210/

相关文章:

java - 数组列表中的对象不断替换?

javascript - 如何清除 jQuery 中的输入字段?

c++ - C++ 中的点云库 (PCL) 等待/延迟/ sleep 函数

c++ - select() 和 FD_ISSET() 成功后 read() 失败

python - 使用父实例初始化子实例

java - 哪些语言 "have subclassing but no inheritance"?

C++:隐藏基本静态成员

c++ - 并行减少(例如求和)hpx::futures<double> 的 vector

c++ - 升级到 Mojave 后无法使用 'hello world' 编译 C++ `#include`

php - 覆盖静态变量