我想检查一下自己是否正确理解了下面来自 C++ 20 标准的引用(英语不是我的母语)。
第 9.7.1 节命名空间定义:
2 In a named-namespace-definition, the identifier is the name of the namespace. If the identifier, when looked up (6.4.1), refers to a namespace-name (but not a namespace-alias) that was introduced in the namespace in which the named-namespace-definition appears or that was introduced in a member of the inline namespace set of that namespace, the namespace-definition extends the previously-declared namespace. Otherwise, the identifier is introduced as a namespace-name into the declarative region in which the named-namespacedefinition appears.
可以在命名空间中定义命名空间,然后在其内联命名空间之一中进行扩展吗?或相反亦然。命名空间可以在内联命名空间中定义,然后在其封闭命名空间中扩展吗?
这是一个演示程序。
#include <iostream>
inline namespace N1
{
inline namespace N2
{
namespace N3
{
void f( int ) { std::cout << "f( int )\n"; }
}
}
namespace N3
{
void f( char ) { std::cout << "f( char )\n"; }
}
}
int main()
{
N3::f( 10 );
N3::f( 'A' );
}
程序输出为
f( int )
f( char )
但是,对于此程序,编译器会发出错误,指出对“N3”的引用不明确。
#include <iostream>
inline namespace N1
{
namespace N3
{
void f( int ) { std::cout << "f( int )\n"; }
}
inline namespace N2
{
namespace N3
{
void f( char ) { std::cout << "f( char )\n"; }
}
}
}
int main()
{
N3::f( 10 );
N3::f( 'A' );
}
最佳答案
may a namespace be defined in a namespace and then extended in one of its inline namespace?
没有。在第二个示例中,当编译器在 N2
中看到 N3
的定义时,N3
的查找会找到 N3
> 在 N2
外部声明,但 N3
并未“在出现命名空间定义的命名空间中引入”(因为它不在 N2 内部
),或“在该命名空间的内联命名空间集的成员中引入”,因为 N2
的内联命名空间集是内部的传递内联命名空间的集合。 N2。因此,N3
的这个新定义不会扩展之前的定义。
May a namespace be defined in an inline namespace and then be extended in its enclosing namespace?
是的。在第一个示例中,N3
查找时发现 N2::N3
,它是“在内联命名空间集的成员中引入的”,因为 N2
是 N1
内联命名空间集的一部分。
我们可以如下理解这种明显不对称的基本原理:在第二个示例中,当 N3
最初定义时,它被定义为 N1
和 < em>不是N1
任何内联命名空间的成员。稍后,在定义N2::N3
时,如果要扩展N1::N3
,则会追溯使得 N3
是 N2
的成员,这违背了常识,因此是不允许的。在第一个示例中,N3
最初被定义为内联命名空间 N2
的成员,稍后使用第二个定义扩展它没有问题。 (虽然我看不出这是有用的明显原因。)
关于c++ - 扩展最初在内联命名空间的封闭命名空间中定义的内联命名空间中的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58526031/