C ++ namespace .... Anonymous namespace is legal?

namespace {int Foo (int a); }

Like it. Is this piece of code legal?

Is it legal? and can i link to foo anywhere? or just a specific domain?

Thanks.

+4
source share
3 answers

It is legal. You can use Foo anywhere in the same Translation Department .

Anonymous namespace is the standard prescribed way of expressing static for variables to limit the scope to the same translation unit.

C ++ 03 Standard Section 7.3.1.1 Namespaces

para 2:

Using a static keyword is deprecated when declaring objects in a namespace scope; an unnamed namespace provides an excellent alternative.


Update:
As @Matthieu M. correctly points out in the comments, and his answer . The C ++ 11 standard removed the above quote from the C ++ 03 Standard, which implies that the static not expired when declaring objects in the namespace scope, the Anonymous or Bezymyanny namespace is still valid.

+8
source

It is legal. You can reference Foo anywhere in the translation unit.

From the C ++ 03 standard, section 7.3.1.1:

A definition without namespace-name behaves as if it were replaced by

 namespace unique { /* empty body */ } using namespace unique; namespace unique { namespace-body } 

where all occurrences of unique in the translation block are replaced by the same identifier, and this identifier is different from all other identifiers in the entire program.

Using the static keyword is deprecated when declaring objects in a namespace scope; an unnamed namespace provides an alternative superiority.

+4
source

The definition has changed a bit in the C ++ 11 standard:

7.3.1.1. Namespaces [namespace.unnamed]

1 / A definition without a namespace-name behaves as if it were replaced by

 inlineoptnamespace unique { /* empty body */ } using namespace unique ; namespace unique { namespace-body } 

where the inline line appears if and only if it appears in the name definition without a name, all occurrences of a unique translation unit are replaced by the same identifier, and this identifier is different 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]

+2
source

All Articles