c++ - 如何解释 c++ 标准中的规则 [namespace.udir]p2?

标签 c++ language-lawyer using-directives name-lookup

我对 [namespace.udir]p2 的含义有点困惑。考虑以下程序:

namespace X { int i = 1; }

namespace Y { using namespace X; }

int main() { i = 2; }

其中 i 的名称查找在 main 中失败(我尝试使用 GCC、Clang 和 Visual C++)。这似乎与 [namespace.udir]p2 ( http://eel.is/c++draft/dcl.dcl#namespace.udir-2 ) 不一致:

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup ([basic.lookup.unqual]), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace. [ Note: In this context, “contains” means “contains directly or indirectly”. — end note ]

在我的程序中,我将此规则应用于名称 i,由 X 中的 int i = 1; 声明,如下所示方式:

  • using 指令:using namespace X;

  • 命名空间:X

  • 最近的封闭命名空间:全局命名空间

这是否意味着 maini 的非限定名称查找应该找到 X::i?为什么我尝试过的三种编译器都没有得到这个结果?

最佳答案

使用指令使名称​​在它们出现的范围内可见。例如,[basic.scope.namespace]p1

for each using-directive that nominates the member’s namespace, the member’s potential scope includes that portion of the potential scope of the using-directive that follows the member’s point of declaration

其中名称的作用域是程序的一部分,可以通过非限定查找找到该名称(该名称的声明)。

类似地,在[namespace.udir]p2中,

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive.

这基本上与上面的引述相同。

在 OP 中,using-directive 出现在命名空间 Y 的命名空间范围内; main 超出该范围,因此 using-directive 对在 main 内执行的名称查找没有影响。

关于c++ - 如何解释 c++ 标准中的规则 [namespace.udir]p2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494906/

相关文章:

c++ - C++ 在避免内存泄漏方面是否比 C 更好?

c - 什么是标签 namespace ?

c++ - break/continue/return 应该被异常打断吗?

ms-access - USING 语句的 VBA 是什么

c++ - 使用 'using' 关键字使继承的构造函数公开

c++ - 崩溃 : Segmentation fault: Boost serialization loading - calling constructor with null

c - 可变修改类型只是 VLA 吗?

javascript - AngularJS 中的指令内部指令?

c# - 为什么我不能写 IO.Directory.GetFiles?

c++ - Valgrind 提示 std string 的新运算符可能存在内存泄漏