如何在多重继承下从一个基类继承所有类型

How to inherit all typedefs from one base class under multiple inheritance?

本文关键字:基类 一个 继承 类型 多重继承      更新时间:2023-10-16

假设我有两个基类,它们有一堆类型定义:

struct X {
  typedef int type1;
  typedef float type2;
  // A bunch of other typedefs.
};
struct Y {
  typedef long type1;
  typedef char type3;
  // Some other typedefs.
};
struct Z : public X, public Y {
};

我如何指定我想让Z从X继承所有类型定义,而不手动解决每个类型的冲突?我指的是O(1)个代码来实现这一点,而不是O(n)个,其中n是冲突类型的数量。同样,在元编程的情况下,人们不知道X和Y中的确切类型,因此手动解决冲突是不可能的。

在单继承的情况下,它会自动使用基类的类型定义,所以我不需要手动指定它们。

嗯,它工作得很好。你只需要解决冲突。

struct X
{
    typedef int type1;
    typedef int type2;
};
struct Y
{
    typedef double type1;
};
struct Z : public X, public Y 
{
    type2 z1;
    typedef X::type1 type1;
    type1 z2;
};
int main()
{
    Z z;
    Z::type2 x;
    Z::type1 y;
}

使用privateprotected继承而不是public继承,然后使用using语句声明要在Z中使用的项,例如:

struct Z : protected X, protected Y
{ 
    using X::type1;
    using X::type2;
    // ...
};