考虑到这种情况:
class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error?
考虑到这种情况:
class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error?
将GrandParent
的构造函数设为私有,将Parent
设为友元。
class GrandParent
{
friend class Parent;
private:
GrandParent() {}
// ...
};
您也可以通过将析构函数设置为私有来权衡多态销毁 GrandParents
:
class GrandParent
{
friend class Parent;
private:
virtual ~GrandParent() {}
};
// Invalid Destruction:
GrandParent* p = new Parent;
...
delete p;
friend
是一个笼统的解决方案。不过我想不出更好的办法了... - rubenvb #include <type_traits>
class Child : public Parent
{
};
static_assert(std::is_base_of<Parent, Child>::value, "Child must derive Parent");
如果你试图将父类更改为祖父类,编译器会报错。
T *
参数的方法,并带有 SFINAE 检查,以检查 T
是否派生自 GrandParent
,他们 可以包含一个 static_assert
,以拒绝任何未从 Parent
派生出来的内容。但这让我想:OP试图实现什么?在那种情况下,更简单和更明智的方法是首先将其限制为Parent
,而不必担心其他源于GrandParent
的类。 - user743382Child2 *
,其中Child2
直接派生自GrandParent
,并且OP将该Child2 *
传递给一个模板函数(可能只是一个签名简单的template <typename T> void f(T *)
),该函数旨在仅与派生自Parent
的类一起使用,那么可以在其中放置检查。如果该函数被广泛使用,那么您就不需要为所有子类重复检查。但是再说一遍 - 在这种情况下,我认为OP的设计可能存在问题。 - user743382static_assert
是其中最重要的部分,并且那是 @АлександрЛысенко的,所以如果它被放在这个答案中,我也没问题。 :) - user743382
Parent
的基类存在,那么为什么需要GrandParent
呢? - Pete Beckerstd::vector
。 - milleniumbug