【问题标题】:Namespace member definition命名空间成员定义
【发布时间】:2011-05-15 02:57:45
【问题描述】:
namespace M{
void f();
void M::f(){}
}
int main(){}
上面的代码给出了这样的错误:
“ComeauTest.c”,第 3 行:错误:
限定名称不允许在
命名空间成员
宣言
无效 M::f(){}
和
G++ 也会报错。
但是
VS2010 编译正常。
我的问题是:
a) 预期的行为是什么?
b) $7.3.1.2 似乎没有谈到这个限制。标准的哪一部分指导此类代码的行为?
【问题讨论】:
标签:
c++
namespaces
definition
member
【解决方案1】:
标准的哪一部分指导此类代码的行为?
C++03 Section $8.3 说
除了在其类之外定义成员函数 (9.3) 或静态数据成员 (9.4)、定义或显式实例化命名空间的函数或变量成员外,声明符 ID 不应被限定在其命名空间之外,或在其命名空间之外定义先前声明的显式特化,或作为另一个类或命名空间成员的友元函数的声明 (11.4)。
所以你的代码格式不正确。
然而,在讨论 issue 548 时,CWG 同意应取消在其命名空间内对合格声明符的禁令1。
1 : 活跃问题482
【解决方案2】:
7.3.1.2-2 专门谈到这个:
Members of a named namespace can also be defined outside that namespace by explicit qualification (3.4.3.2) of the name being defined, provided that the entity being defined was already declared in the namespace and the definition appears after the point of declaration in a namespace that encloses the declaration’s namespace.
M::f 被认为是在命名空间定义之外。