c++依赖于派生类的纯虚拟函数
c++ Pure virtual functions dependent on derived classes
我正在开发一个边界盒/碰撞检测系统,我使用不同类型的边界体,像所有边界体一样派生出相同的基类,然后使用纯虚拟函数强制所有派生类实现等基本函数
isCollidingWith(BoudingBox)
但这给我带来了麻烦:我不希望他们为每个BoudingVolume
类型实现一个函数。因此,如果我有一个边界框和一个边界球体,那么球体类和框类都应该实现
isCollidingWith(BoundingBox)
isCollidingWith(BoundingSphere)
如果我创建了一个类似BoundingCylinder
的新BoundingVolume(通过从基类派生),我希望编译器抛出一个错误,直到BoundingBox和BoundingSphere为新的Cylinder
类型实现了isCollidingWith
函数(并且直到Cylinder
为Box
、Sphere
和Cylinder
实现了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
的相互依赖性。
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数