【问题标题】:Partial specialization of member variable and method成员变量和方法的部分特化
【发布时间】:2012-06-02 21:26:35
【问题描述】:

我正在编写一个既适用于 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 的代码,因为我的表面数组和修改函数是唯一指定它的成员。那么还有其他方法吗?

【问题讨论】:

  • 一次抽象你的surface 怎么样?您可以对最高因子方法使用的抽象概念进行两种特殊化。

标签: c++ templates code-organization template-specialization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2011-06-16
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多