Search code examples
c++namespaceslanguage-lawyerusing-declarationunnamed-namespace

Why is an unnamed namespace not equivalent to a regular namespace with a "using namespace" declaration?


A recent thread on SO triggerred this.

An unnamed namespace is considered to be equivalent to

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

I fail to recollect the exact reason as to why it is not equivalent to

  namespace unique { namespace-body } 
  using namespace unique;

Also tried searching (including google) but in vain. Please share any information you have in this regards.


Solution

  • The specification that exists now was introduced in 1995 in N0783 to correct for a corner case. To quote that paper (page 9):

    The WP defines the semantics of an unnamed namespace as being equivalent to:

    namespace UNIQUE {
        // namespace body
    }
    using namespace UNIQUE;
    

    This is incorrect because it makes the code in an unnamed namespace dependent on whether the code is in an original namespace or a namespace extension.

    namespace {} // If you remove this line, the
                 // use of ::f below is invalid
    
    namespace {
        void f()
        {
            using ::f;
        }
    }
    

    The WP should be changed to define an unnamed namespace as being equivalent to:

    namespace UNIQUE {}
    using namespace UNIQUE;
    namespace UNIQUE {
        // namespace body
    }