Revert to unnamed namespace after importing another namespace within same scope

44 views Asked by At

I have the following code from a textbook:

namespace sally {
    void message( ) {
        std::cout << "Hello from Sally.\n";
    }
} 

namespace {
    void message( ) {
        std::cout << "Hello from unnamed.\n";
    }
}

int main( ) {
    message(); 
    {
        message( );
        using sally::message;
        message( );
    }
    return 0;
} 

The code using sally::message; changes the default call to the function message() to be the call from the namespace sally. If I wanted to call message() from the unnamed namespace, I do know that I can use ::message().

But is it possible to change the default call to message() (within the scope) back to the function from the unnamed namespace?

1

There are 1 answers

0
Artyer On

You can bring in (anonymous)::message seperately with using ::message;:

int main( ) {
    message(); 
    {
        message( );
        using sally::message;
        message( );
        {
            using ::message;
            message( );  // Lookup finds `::message` (introduced above) and stops looking in outer block scopes
        }
    }
    return 0;
}

It has to be in a new block scope because if it was in the same scope, message() would be ambiguous.