c++依赖于派生类的纯虚拟函数

c++ Pure virtual functions dependent on derived classes

本文关键字:虚拟 函数 依赖于 派生 c++      更新时间:2023-10-16

我正在开发一个边界盒/碰撞检测系统,我使用不同类型的边界体,像所有边界体一样派生出相同的基类,然后使用纯虚拟函数强制所有派生类实现等基本函数

  • isCollidingWith(BoudingBox)

但这给我带来了麻烦:我不希望他们为每个BoudingVolume类型实现一个函数。因此,如果我有一个边界框和一个边界球体,那么球体类和框类都应该实现

  • isCollidingWith(BoundingBox)
  • isCollidingWith(BoundingSphere)

如果我创建了一个类似BoundingCylinder的新BoundingVolume(通过从基类派生),我希望编译器抛出一个错误,直到BoundingBox和BoundingSphere为新的Cylinder类型实现了isCollidingWith函数(并且直到CylinderBoxSphereCylinder实现了isCollidingWith为止)。

我不确定如何实现这一点,但我考虑过使用CRT。这可能吗?

当您在基类中使纯虚拟函数时,派生类必须实现它,如果派生类没有实现它,编译器将给您一个错误。因此,您不必关心是否实现了纯虚拟函数。

用CRTP 调制这样的东西是可能的

class BoundingBox;
class BoundingSphere;
class Shape
{
public:
virtual bool isIntersecting(const BoundingBox&) const = 0;
virtual bool isIntersecting(const BoundingSphere&) const = 0;
};
class BoundingVolumeBase
{
public:
virtual bool checkIntersection(const Shape&) const = 0;
virtual ~BoundingVolumeBase();
};
template<class Derived>
class BoundingVolume : public BoundingVolumeBase
{
bool checkIntersection(const Shape& shape) const override
{
return shape.isIntersecting (static_cast<const Derived&>(*this));
}
};
class BoundingBox : public BoundingVolume<BoundingBox> {
// ...
};
class BoundingSphere : public BoundingVolume<BoundingSphere> {
// ...
};

现在,如果我们发明了一种新的BoundingVolume,它将不会编译,直到在Shape中添加了一个新函数。

class BoundingCylinder : public BoundingVolume<BoundingCylinder> {
// ...
};
BoundingCylinder bc; // <-- this will not compile

没有必要这样做。任何使用虚拟函数作为唯一一种基于类型的调度的方法都会起作用(无论如何,您最终可能会得到与上述大致等效的结果)。如果您依赖typeid或自定义类型标识符,则可能会遇到问题。

该方法的缺点是类Shape所有具体类型的BoundingVolume的相互依赖性。