我想提供从子类中的基类访问现有类型的权限。
我发现了两种不同的方式:
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/