namespace { int Foo (int a) ; }
Like this. Is this code snippet legal?
Is this legal? and, can I reference Foo in anywhere? or only certain domain?
Thank you.
namespace { int Foo (int a) ; }
Like this. Is this code snippet legal?
Is this legal? and, can I reference Foo in anywhere? or only certain domain?
Thank you.
It is legal, You can use Foo
anywhere in the same Translation Unit.
Anonymous namespace is the standard prescribed way of saying static
on variables to limit their scope to the same Translation unit.
C++03 Standard section 7.3.1.1 Unnamed namespaces
para 2:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.
Update:
As @Matthieu M. correctly points out in the comments, and his answer The C++11 Standard removed the above quote from C++03 Standard, which implies that the static
keyword is not deprecated when declaring objects in a namespace scope, Anonymous or Unnamed namespaces are still valid nevertheless.
This is legal. You can reference Foo
anywhere inside the translation-unit.
From the C++03-standard, Section 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.
The definition changed slightly in the C++11 Standard:
7.3.1.1 Unnamed namespaces [namespace.unnamed]
1/ An unnamed-namespace-definition behaves as if it were replaced by
inlineoptnamespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }
where inline appears if and only if it appears in the unnamed-namespace-definition, 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.94 [ Example:
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 ]