使C++模拟类同时使用 2D 和 3D 矢量

Making a C++ Simulation-Class work both with 2D- and 3D-Vectors

本文关键字:3D 矢量 2D C++ 模拟类      更新时间:2023-10-16

d我正在编程一个模拟。现在它应该同时适用于 2D 和 3D,所以我正在尝试让我的类使用 2D 和 3D 矢量。此外,矢量应具有模板参数,以指示应将哪种类型用于坐标。

我的基类如下所示:

class SimulationObject {
    AbstractVector<int>* position;
    AbstractVector<float>* direction;
}

现在的问题是,我不能使用多态性,因为那时我所有的 Vector 都必须是指针,这使得运算符重载几乎不可能用于这样的操作:

AbstractVector<float>* difference = A.position - (B.position + B.direction) + A.direction;

但我也不能使用模板参数来指定要使用的类型:

template <typename T> class Vector2d;
template <typename T> class Vector3d;
template <class VectorType> class SimulationObject {
    VectorType<int> position;
    VectorType<float> direction;
}

SimulationObject<Vector2D> bla; 
//fails, expects SimulationObject< Vector2D<int> > for example.
//But I don't want to allow to specify
//the numbertype from outside of the SimulationObject class

那么,怎么办呢?

您可以使用模板模板参数:

template <template <class> class VectorType> 
class SimulationObject {
    VectorType<int> position;
    VectorType<float> direction;
};