命名空间 { int Foo(int a); }
像这样。 这段代码合法吗?
这合法吗? 我可以在任何地方引用Foo吗? 还是只能在特定域中使用?
谢谢。
命名空间 { int Foo(int a); }
像这样。 这段代码合法吗?
这合法吗? 我可以在任何地方引用Foo吗? 还是只能在特定域中使用?
谢谢。
static
关键字的使用不再被描述为过时的规定 :) - Matthieu M.static
。 - Björn Pollex这是合法的。您可以在翻译单元内的任何地方引用Foo
。
根据C++03标准,第7.3.1.1节:
An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ } using namespace unique; namespace unique { namespace-body }
where all occurrences of
unique
in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.
unique
(这是该命名空间的名称)对于所有的翻译单元都不相同,所以你永远不会有重复定义的符号。此外,这是标准中的一句引文,如果你有异议,请向委员会提出。 - Björn Pollexunique
只是一个名称。我不知道标准委员会会给出这样令人困惑的例子 :))。也许 namespace <unique name> { ... } using namespace <unique name>;
会是更合适的措辞。 - iammilindC++11标准中,该定义略有变化:
7.3.1.1 匿名命名空间 [namespace.unnamed]
1/ 匿名命名空间定义的行为就像被以下内容所替换:
inlineoptnamespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }
当 inline 函数或变量出现在未命名命名空间定义中时,所有翻译单元内的 unique 函数或变量都将被替换为相同的标识符,并且该标识符与整个程序中的所有其他标识符均不同。94 [ 例如:
namespace { int i; } // unique ::i
void f() { i++; } // unique ::i++
namespace A {
namespace {
int i; // A:: unique ::i
int j; // A:: unique ::j
}
void g() { i++; } // A:: unique ::i++
}
using namespace A;
void h() {
i++; // error: unique ::i or A:: unique ::i
A::i++; // A:: unique ::i
j++; // A:: unique ::j
}
—end example ]