gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:46:00 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com