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

标签 c++ namespaces

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

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/

相关文章:

c++ - 为什么 LD_LIBRARY_PATH 无效?

C++ 命名空间/标识符问题

c++ - 为什么派生类不能访问 protected 基类成员?

ruby-on-rails - 命名空间修改后表单损坏

r - 从另一个包中调用时,无法从 mgcv 访问 "ldTweedie"函数

c++ - 在堆栈与堆上对派生类对象使用基类指针

c++ - 混淆后缀表达式和运算符的语法

javascript - 一个文件中的两个js文件

c++ - (Gnome) 桌面通知如何工作?

C++ 递归 Febonacci 函数