成员变量和方法的部分特化



我正在编写一个模拟,它应该适用于2D和3D。现在我得到了应该修改表面的对象。在3D时,表面是二维阵列,而在2D时,表面是一维的。我使用模板参数来指示我使用哪个维度空间。但是当我专门化数组的类型时,我无法专门化修改函数,因为它在指定的类中是预期的。然后我将不得不将所有成员复制到专业类中。

template <class VectorType> class SimulationObject {
    void operateOnSurface();
};
template<> class SimulationObject<Vector2D> {
    char* surface;
 // Declaration of operateOnSurface expected here
};
template<> class SimulationObject<Vector3D> {
    char** surface;
// Declaration of operateOnSurface expected here
};
template<> void A<Vector2D>::operateOnSurface() {
}
template<> void A<Vector3D>::operateOnSurface() {
}

但我仍然想避免复制 2d 和 3d 的代码,因为我的表面数组和修改函数是唯一指定它的成员。那么还有别的办法吗?

如果您可以访问 Vector2D 和 Vector3D,您可以为它们添加一个 static const int dimensions; 变量并使用 VectorType::dimensions 访问它。

最新更新