c++ - 如何正确引用匿名命名空间中的函数

标签 c++ visual-c++ gcc namespaces language-lawyer

考虑一下这段 C++ 代码:

namespace
{
    void f()
    {
    }

    class A
    {
        void f()
        {
            ::f(); // VC++: error C2039: 'f' : is not a member of '`global namespace''
        }
    };
}

GCC 编译得很好。 Visual C++ 2008 编译失败,出现 C2039 错误。这两个编译器中的哪一个在这里是正确的?有什么方法可以正确引用 "global" f 吗?

编辑: Zack 建议尝试一下,它适用于两种编译器。我觉得有点奇怪。

namespace
{
    void f()
    {
    }

    class A
    {
        void f();
    };
}

void A::f()
{
    ::f();
}

最佳答案

VC++ 2008 在这里是错误的。根据c++03标准3.4.3.4:

A name prefixed by the unary scope operator :: (5.1) is looked up in global scope, in the translation unit where it is used. The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global scope because of a using-directive (3.4.3.2). The use of :: allows a global name to be referred to even if its identifier has been hidden (3.3.7).

这里的重要部分是全局命名空间中的 using 指令将使这些符号可以通过范围运算符访问。

并且根据 7.3.1.1/1,匿名命名空间相当于:

namespace *unique* { /* empty body */ }
using namespace *unique*;
namespace *unique* { namespace-body }

所以在这两个部分之间,独立函数应该可以在全局命名空间中访问。

关于c++ - 如何正确引用匿名命名空间中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5503901/

相关文章:

c++ - dynamic_cast 何时因隐藏符号而失败?

c - 如何使用 GCC 取消引用零地址?

c++ - winhttp.dll 中的访问冲突

c++ - 从成员指针获取类/结构对象

c++ - 从 catch block 重新抛出异常时丢失异常类型

c++ - OpenGL SuperBible 6 第一个例子报错

c++ - 如何解决 g++ 问题 "internal compiler error: Illegal instruction min() _GLIBCXX_USE_NOEXCEPT { return __FLT_MIN__; }"?

c++ - std::string 到 c 字符串的转换 mosquitto

c++ - 在哪里可以找到将 VC++ 内联汇编程序转换为内在函数的脚本?

visual-c++ - SetWindowPos() 函数不移动窗口?