gpt4 book ai didi

c++ - 嵌套未命名的命名空间

转载 作者:IT老高 更新时间:2023-10-28 22:30:16 25 4
gpt4 key购买 nike

这两种未命名命名空间的嵌套用法之间是否存在功能差异:

namespace A { namespace {
void foo() {/*...*/}
}}

namespace { namespace A {
void foo() {/*...*/}
}}

据我所见,两个 foo 都将获得每个编译单元的内部唯一标识符,并且可以使用 A::foo 进行访问 - 但是否存在我没有看到的细微或不那么细微的区别?

最佳答案

和你输入的完全一样,没有区别。

当然,你可以在展位示例的第一级命名空间中添加声明,然后就会有所不同。

namespace A {
int i; // Accessed globally in this file as "A::i".
namespace {
void foo() {/*...*/}
}}


namespace {
int i; // Accessed globally in this file simply as "i".
namespace A {
void foo() {/*...*/}
}}}

请注意,尽管您的程序员无法区分,但对于编译器来说,命名空间是不同的:

unnamed_namespaces.cpp:42:5: error: reference to ‘A’ is ambiguous
unnamed_namespaces.cpp:19:17: error: candidates are: namespace A { }
unnamed_namespaces.cpp:28:19: error: namespace <unnamed>::A { }

有用:


编辑:

关于 ADL(依赖于参数的名称查找),我知道对于其他 foo() 的重载解析将没有优先级差异,如下所示:

#include    <iostream>

void foo() { std::cout << "::foo()" << std::endl; }

namespace A {
namespace {
void foo() { std::cout << "A::<unnamed>::foo()" << std::endl; }

class AClass
{
public:
AClass( )
{ foo( ); }
};
}
}


namespace {
namespace B {
void foo() { std::cout << "B::<unnamed>::foo()" << std::endl; }

using namespace A;

class BClass
{
public:
BClass( )
{ foo( ); }

~BClass( )
{ A::foo( ); }
};
}
}

int main( )
{
A::foo( );
B::foo( );
foo( );

A::AClass a;
B::BClass b;

return 0;
}

除非明确指定,否则编译器将优先选择最接近的 foo( )。所以 BClass 构造函数调用 B::foo( ) 甚至有一个 using namespace A 。要在 BClass 析构函数上调用 A::foo( ),调用必须显式限定。

A::<unnamed>::foo()
B::<unnamed>::foo()
::foo()
A::<unnamed>::foo()
B::<unnamed>::foo()
A::<unnamed>::foo()

如果我们考虑嵌套的 named 命名空间以及如何解决与参数相关的问题,也许会更清楚。唯一的区别是隐式 using 在未命名的那些上,但它不会改变编译器的偏好。

关于c++ - 嵌套未命名的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358478/

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