c++ - 使用基类中现有类型的声明与在子类中创建类型别名

标签 c++ typedef type-alias using-declaration

我想提供从子类中的基类访问现有类型的权限。

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

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
};
  1. 有什么区别吗?
  2. 每种语法的优缺点是什么?
  3. 哪个是最常用/最推荐的?

谢谢。

相关问题: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/

相关文章:

c++ - 从派生类中的模板化基类使用 typedef/using

c++ - 头文件中声明的 typedef 在源文件中不可用

ios - 使用协议(protocol)创建类型别名

Scala 类型别名,包括伴随对象 [初学者]

swift - 在 Swift 中,如何扩展类型别名?

c++ - Docker容器中的可执行文件不会从gdb远程调试中注册断点

c++ - C++类的大小是如何确定的?

c++ - 在调用实际析构函数之前删除了字段变量?

形式参数可以与类型同名吗? (C)

java - 在 C++ 中嵌入 GWT?