c++ - 非限定名称查找找到内联命名空间成员

标签 c++ c++11 namespaces inline language-lawyer

我写了下面的代码:

   #include <iostream>

    inline namespace M
    {
        int j=42;
    }

    int main(){ std::cout << j << "\n"; } //j is unqualified name here. 
                 //Hence, unqualified name lookup rules will be applied.
                 //This implies that member of inline namespace shall not be considered. 
                 //But it is not true

而且效果很好。但我预计该程序格式错误。这是因为标准说(N3797,第 7.3.1/7 节):

Finally, looking up a name in the enclosing namespace via explicit qualification (3.4.3.2) will include members of the inline namespace brought in by the using-directive even if there are declarations of that name in the enclosing namespace.

此外,3.4.1/6 节没有提及在非限定名称查找中涉及内联命名空间:

A name used in the definition of a function following the function’s declarator-id 28 that is a member of namespace N (where, only for the purpose of exposition, N could represent the global scope) shall be declared before its use in the block in which it is used or in one of its enclosing blocks (6.3) or, shall be declared before its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N’s enclosing namespaces.

这是一个 g++ 错误,还是我理解的规则不正确?

最佳答案

没有错误..

不,它不是 g++(或 clang++)中的错误,它具有所描述的行为,编译器应该找到 j .

inline namespace N {
  int j;
}

int main () {
  int a = j; // legal, `j` == `N::j`
}

标准怎么说?

您遗漏了标准的一个非常重要的部分,即 7.3.1§8,其中声明内联命名空间的封闭命名空间隐式有一个 < em>using 指令 引用内联命名空间。

[7.3.1]p8 namespace definition [namespace.def]

Members of an inline namespace can be used in most respects as thought they were members of the enclosing namespace. Specifically, the inline namespace and its enclosing namespace are both added to the set of associated namespaces used in argument-dependent lookup (3.4.2) whenever one of them is, and a using-directive (7.3.4) that names the inline namespace is implicitly inserted into the enclosing namespace as for an unnamed namespace (7.3.1.1).


阐述

这意味着我们前面的示例在语义上等同于下面的示例,其中我们引入了一个using-directive 以将名称从我们的嵌套命名空间引入全局命名空间:

inline namespace N {
  int j;
}

using namespace N; // the implicit using-directive    

int main () {
  int a = j; // legal
}

关于c++ - 非限定名称查找找到内联命名空间成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228299/

相关文章:

c++ - boost::threads 程序导致大量竞争条件

c++ - C++中的命名空间如何链接?

c# - .Net 命名空间可以跨越多个程序集吗?

namespaces - TCL中命名空间/上级/全局的使用

c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?

c++ - 在 C++ 中初始化对象数组时出错

c++ - 如何开始使用 Android Studio C++ 开发

c++ - 在 KDE 上清除剪贴板

c++ - 即使在使用命名空间指令后也没有歧义引用错误

c++ - lambda如何捕获局部静态变量?