命名空间内的本地函数声明

时间:2013-01-03 18:31:23

标签: c++ namespaces function-declaration

在这种情况下

namespace n {
    void f() {
        void another_function();
    }
}

是否应在命名空间another_function内或外部定义函数n? VS 2012(November CTP)表示它应该在外面,而Mac上的GCC 4.7.2表示它应该在里面。如果我做错了,我会从链接器中得到未定义的符号错误。

我普遍相信GCC更符合标准,但这是C ++,你永远无法确定。

2 个答案:

答案 0 :(得分:11)

C ++ 11 3.5(以及C ++ 03)

  

7 当找不到具有链接的实体的块范围声明时   引用一些其他声明,然后该实体是其成员   最里面的封闭命名空间。但是这样的声明却没有   在名称空间范围内引入成员名称。

示例中的声明声明n::another_function

答案 1 :(得分:3)

根据N3485 7.3.1 [namespace.def] / 6,正确答案为n::another_function

  

声明的封闭命名空间是其中的命名空间   声明词汇出现,除了重新声明   在其原始命名空间之外的命名空间成员(例如,定义   如7.3.1.2中所述。这种重新声明具有相同的封闭性   名称空间作为原始声明。 [例如:

namespace Q {
    namespace V {
        void f(); // enclosing namespaces are the global namespace, Q, and Q::V
        class C { void m(); };
    }
    void V::f() { // enclosing namespaces are the global namespace, Q, and Q::V
        extern void h(); // ... so this declares Q::V::h
    }
    void V::C::m() { // enclosing namespaces are the global namespace, Q, and Q::V
    }
}
     

-end example]