c++ - 对内部类型使用声明

标签 c++

<分区>

使用类成员声明只允许作为成员声明的原因是什么?我做不到

struct Outer
{
    typedef int Inner;
};

void f()
{
// this doesn't work with C++14
     using Outer::Inner;
}

,但我认为这与使用声明将在其他地方声明的名称引入当前区域的预期语义相当正交。它受到 C++ 标准的明确限制

7.3.3/8: A using-declaration for a class member shall be a member-declaration

,但我想知道为什么。

我认为如果允许使用内部类型(typedef、类等)并定义为与

// using Outer::Inner should be identical to
using Inner = Outer::Inner

,这与命名空间的行为相同。

我知道这个问题has been asked before ,但公认的答案是禁止的,因为标准是这样说的。我想知道这背后是否有任何技术原因。在其中一条评论中,据说

Making the Standard (and therefore all compilers) more complicated to handle an unusual case that has a convenient workaround just doesn't pass the cost-benefit test.

我想说这是一种观点而不是争论。改变它使语言变得更加统一是一个巨大的好处。现在,你必须教不同的东西来做同样的事情。如果删除该子句,标准将变得更简单,这既是因为大小减小了,也是因为(无缝任意的)特殊情况被删除了。

更准确地说,我正在寻找技术原因为什么不允许这样做,例如会产生歧义或其他问题的地方。

最佳答案

不要混淆使用声明和别名声明。 using A = B; 是一个别名声明,在语义上与 typedef 相同:

A typedef-name can also be introduced by an alias-declaration . The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name . It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id .

因此,您使用 Inner = Outer::Inner 编写,因为它与 typedef Outer::Inner Inner 相同,而不仅仅是 typedef Outer::Inner alias-declaration 为类型名称创建别名。

另一方面,using-declaration 是不同的东西:它在范围 (7.3.3/1) 中引入了一个名称,但它也被单词 using 调用,这有点令人困惑。

所以,

// using Outer::Inner should be identical to using Inner = Outer::Inner

它们不能完全相同,它们是不同的东西。

关于c++ - 对内部类型使用声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33212696/

相关文章:

c++ - 我想使用 I2C 从 arduino 接收多个数据到 raspberry pi

c++ - DBus与其他进程间通信方式的区别

c++ - 为 STL 随机数生成器编写工厂方法

C++:如何将 GUID 设置为 NULL 而不是 GUID_NULL?

c++ - 用于浏览 C/C++ 项目中的类的软件

c++ - (简单 C++)从文件中获取带有 vector 的矩阵

c++ - C++中的调制解调器调用

c++ - ThreadSanitizer 的抑制文件不起作用 : What is wrong?

c++ - 为什么传递位置参数时总是得到默认值?

c++ - getchar()有什么用?