我想提供子类中基类对现有类型的访问。

我发现了两种不同的方式:

struct A {
    typedef int mytype;
};

struct B {
    typedef double mytype;
};


我可以使用using声明“包含”类型:

struct C : A, B {
    using typename A::mytype;
};


或者我可以创建一个类型别名:

struct C : A, B {
    typedef A::mytype mytype;
    using mytype = A::mytype; //C++11
};



有什么区别吗?
每种语法的优缺点是什么?
哪个是最常用/推荐的?


谢谢。

相关问题:Using-declaration of an existing namespace type vs creating a type alias

最佳答案

它们是有区别的。考虑一下,如果将结构A和B定义为:

struct A {
protected:
    int mytype;
};

struct B {
protected:
    double mytype;
};


在这种情况下

struct C : A, B {
    using typename A::mytype;  // Would compile, but is mytype a type or
                               // an exposed member of the base class?
    //using mytype = A::mytype;  // Would not compile
};


在您的情况下,我建议使用using mytype = A::mytype;,因为它不太明确。

关于c++ - 使用基类中现有类型的声明与在子类中创建类型别名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58449034/

10-11 22:33
查看更多