Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

c++ - Unqualified name lookup: Why local declaration hides declaration from using directive

Consider this code:

namespace A
{
   int i = 24;
}

namespace B
{
    using namespace A;
    int i = 11;

    int k = i; // finds B::i, no ambiguity
}

And basic.lookup.unqual.2:

§6.4.1 Unqualified name lookup [basic.lookup.unqual]

  1. The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see [namespace.udir]. For the purpose of the unqualified name lookup rules described in [basic.lookup.unqual], the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace.

For me the standard says pretty clear that for the purpose of unqualified name lookup (the i in int k = i) the declaration of i from A is considered member of B so i should be ambiguous in int k = i, however both gcc and clang compile and resolve i to the local B::i. I have searched the standard (basic.scope.hiding and namespace.udir) and did not find an exception or a rule to contradict the above one. I have found that for qualified name lookup, but not for unqualified name lookup.

Why is i unambiguous?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The key is 10.3.4/2 "During unqualified name lookup, the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace."

The nominated namespace is A, the using directive is in B, and the smallest (in fact only) common namespace is the global namespace. Thus i appears as if declared in the global namespace, and is hidden by B::i.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...