gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:48 25 4
gpt4 key购买 nike

我写了下面的代码:

   #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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com