4 A name having namespace scope has external linkage if it is the name of
— a namespace (7.3), unless it is declared within an unnamed namespace.
...全文
1585打赏收藏
C++标准那个文档编写得也太不尽业了
RT ISO/IEC 14882:1998 refer to 3.5.4 4 A name having namespace scope has external linkage if it is the name of — a namespace (7.3), unless it is declared within an unnamed namespace.
自从C++引入namespace的概念之后,一个 name 就有了两层限制:一个是声明限制,一个是 namespace 的限制。要访问一个名字,两者缺一不可(全局namespace除外)。所以定义在无名空间中的 name 不能在其它编译单位中使用是因为在其它编译单位中给不出这个 name 的 namespace,而不是声明(包含了连接属性)上的限制。
to whyglinux(山青水秀):
感觉上是没什么不妥的。看是看看下面这个代码
namespace{
char buffer[256];
}
Refer to 3.5.2
A name is said to have linkage when it maight denote the same object, reference, function, type, template, namespace or value as a name introduced by a declaration in another scope:
- When a name has external linkage, the entity it denotes can be referred to bye names form scopes of other translation units or form other scopes of the same translation unit.
- When a name has internal linkage, the entity it denotes can be referred to by names form other scopes in the same translation unit.
按照标准上的意思,那么buffer就是internal linkage,因为这个buffer不能在其他的translation unit当中被引用。
但事实上又并不是这样
template<char * P>
class X{};
X<buffer> x; //可以编译通过!
Refer to 14.3.2.1
A template-augument for a non-type, non-template template-parameter shall be on of:
- the name of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as id-expression;
按照标准上的说法,X<buffer> x;可以编译通过,是因为buffer是external linkage.
两点矛盾了~~~
我用Google狗到了下面的一段话来解释这个问题。
an unnamed namespace restricts the visibility of its members to the scope of the translation unit by means of name mangling, it doesn't necessarily guarantee internal linkage