What does a leading :: mean in “using namespace ::X” in C++

前端 未结 4 1446
南旧
南旧 2020-12-31 03:51

can somebody explain me the difference between the following namespace usages:

using namespace ::layer::module;

and

using namespa

4条回答
  •  死守一世寂寞
    2020-12-31 04:49

    A leading :: refers to the global namespace. Any qualified identifier starting with a :: will always refer to some identifier in the global namespace. The difference is when you have the same stuff in the global as well as in some local namespace:

    namespace layer { namespace module {
        void f();
    } }
    
    namespace blah { 
      namespace layer { namespace module {
          void f();
      } }
    
      using namespace layer::module // note: no leading ::
                                    // refers to local namespace layer
      void g() {
        f(); // calls blah::layer::module::f();
      }
    }
    
    namespace blubb {
      namespace layer { namespace module {
          void f();
      } }
    
      using namespace ::layer::module // note: leading ::
                                      // refers to global namespace layer
      void g() {
        f(); // calls ::layer::module::f();
      }
    }
    

提交回复
热议问题