如何在多重继承下从一个基类继承所有类型
How to inherit all typedefs from one base class under multiple inheritance?
假设我有两个基类,它们有一堆类型定义:
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;
}
使用private
或protected
继承而不是public
继承,然后使用using
语句声明要在Z
中使用的项,例如:
struct Z : protected X, protected Y
{
using X::type1;
using X::type2;
// ...
};
相关文章:
- 如何定义一个纯抽象基类
- 当基类是依赖类型时,这是一个缺陷吗
- 一个Q_PROPERTY可以泛化为多个基类吗?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- C++多态性:如何测试一个类是否派生自另一个基类
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- 为什么第一个Dynamic_cast没有投射到基类?
- 如果我们有一个基*类,如何访问派生模板类的成员函数
- 如何构建一个 Map,其中键是抽象基类(而不是值)
- C :基类调用自己的虚拟函数 - 一个反图案
- 使从一个基类派生的类能够使用继承的受保护成员
- 摧毁一个不可破坏的基类?
- CRTP - 是否可以创建一个抽象基类?
- 无法从派生的一个方法调用基类方法
- 将函数上调整到基类参数的另一个
- 动态创建一个继承的类,使用STD :: MAP使用基类指针访问
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 如何从另一个类的基类访问派生类中的受保护成员