简体   繁体   中英

Namespace name must be unique to scope. Why?

It might seem obvious why a namespace name must be unique within its scope:

namespace test{}

int test = 10; //error 'int test' redeclared as different kind of symbol

But it seems that the compiler is able to distinguish whether a name is referring to a variable or a namespace:

#include <iostream>

namespace test{
    int x = 2;
}

int main(){

    int test = 5;

    using namespace test; //I was expecting an error to occur here.
    std::cout << test::x << std::endl;

}

In this code the compiler (g++ 5.2.0) does not kick up a fuss about the using directive of test or using the scope operator on test despite the fact that there is a local variable called test . The context seems to make it clear that it's referring to a namespace and thus name lookup (if name lookup even occurs) skips pasts the int variable test to find the namespace in global scope.

Hence why was the first example a problem if the compiler can distinguish uses of namespaces? Is there a context in which an expression might be referring to either a variable or a namespace?

Two different declarations of the same name at the same scope is what causes a problem.

In your second example, the namespace is at an outer scope, and the variable definition at an inner scope. That gives an unambiguous way to decide between the two. It's still possible to create ambiguity in a few cases, but at least the definitions themselves don't collide.

In your first example, you could define a language that allowed ambiguous definitions in the same scope, as long as each was only ever used in a way that wasn't ambiguous. The designers of C++ decided to avoid that, however (and IMO, rightly so--if anything, C++ already allows far too much that strikes most people as ambiguous, even though the rules do make clear what the compiler needs to do).

As for the second example being able to find the namespace even though it's defined at an outer scope, where it's shadowed (hidden) by the variable definition: that's true, but you're only allowed to define a namespace outside any function, so in a using directive (your using namespace ... ) the compiler never even looks inside the function to see the variable definition, because you couldn't define a namespace there, regardless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM