是否有可能在编译时阻止特定基类的多重继承? [英] Is it possible to prevent multiple inheritance of specific base classes at compile time?

查看:146
本文介绍了是否有可能在编译时阻止特定基类的多重继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是开发两个不同的基类,它们不应该在一个派生类中一起继承。有没有什么方法可以在编译时强制执行?

What I am looking to do is develop two different base classes which should not be inherited together in the one derived class. Is there any way I can enforce this at compile time?

class Base1 {};
class Base2 {};
class Derived1 : public Base1 {} // OK!
class Derived2 : public Base2, public Other {} // OK!
class Derived3 : public Base1, Base2 {} // Can I force the compiler to complain?

Derived1 d1; // OK!
Derived2 d2; // OK!
Derived3 d3; // Or can I force the compiler to complain here?

我知道文档是一个好主意,只是想知道是否可能。

I'm aware that documentation is a good idea, just wondering if it is possible.

推荐答案

您正在设置Base1和Base2之间的某种耦合,因为它们不能同时派生。

You are setting up some kind of coupling between Base1 and Base2 in that they cannot both be derived from.

你可以让它们都派生自Base0,在这种情况下,如果你派生自Base1和Base2,你会得到多继承的钻石,所以你会得到一个编译器错误,假设你不使用虚拟继承,你不解决重复。

You could make them both derive from Base0 in which case if you derive from Base1 and Base2 you would get the multiple inheritance diamond so you would get a compiler error assuming you do not use virtual inheritance and you do not resolve the duplication.

这可能解决你的问题,但我怀疑你为什么这么做。

That might solve your problem but I question why you are trying to do this.

(Base0不应该是一个完全空的类,因为必须有一些不明确的东西,导致编译器抱怨,当然你可以解决它,所以它不会完全阻止你从两个派生,

(Base0 should not be a totally empty class as there has to be something there ambiguous to cause the compiler to complain. And of course you could resolve it so it won't totally prevent you deriving from both, just that it will generate the required compiler "error" if you do it by mistake).

一个例子可能是:

class Base0 
{ 
  protected: 
    virtual ~Base0(){};
    virtual void abstractMethod() const = 0;
};

class Base1 : public Base0
{ 
   protected:
     virtual void abstractMethod() const;

   // rest of Base1
};

class Base2 : public Base0
{ 
   protected:
     virtual void abstractMethod() const;

   // rest of Base1
};

class Derived : public Base1, public Base2
{  
  // if I don't resolve abstractMethod it is ambiguous and the compiler will let me know
};

这篇关于是否有可能在编译时阻止特定基类的多重继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆