Lookup with using namespace

Hi,
I was wondering why this prints "unqual" and not "qual" since I have "using namespace a" before calling fun. I though that would be equivalant to having a::fun() which should print "qual".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>

namespace a
{
    void fun()
    {
        std::cout << "qual" << std::endl;
    }
    
    namespace b
    {
        void fun()
        {
            std::cout << "unqual" << std::endl;
        }
        using namespace a;
        void fi()
        {
            fun();
        }
    }
}

int main()
{
    a::b::fi();
}
https://en.cppreference.com/w/cpp/language/namespace#Using-directives
every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name.

In your code the "nearest enclosing namespace" is namespace a. So a::fun() is still treated as being declared in namespace a and that is why a::b::fun() is still chosen on line 19.
Last edited on
Or perhaps the "nearest enclosing namespace" is really the global namespace, because namespace a doesn't contain itself, but that doesn't make any difference.
Topic archived. No new replies allowed.