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

前端 未结 4 1429
南旧
南旧 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:35

    The second case might be X::layer::module where using namespace X has already happened.

    In the first case the prefix :: means "compiler, don't be clever, start at the global namespace".

    0 讨论(0)
  • 2020-12-31 04:48

    There would be a difference if it was used in a context such as:

    namespace layer {
        namespace module {
            int x;
        }
    }
    
    namespace nest {
        namespace layer {
            namespace module {
                int x;
            }
        }
        using namespace /*::*/layer::module;
    }
    

    With the initial :: the first x would be visible after the using directive, without it the second x inside nest::layer::module would be made visible.

    0 讨论(0)
  • 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();
      }
    }
    
    0 讨论(0)
  • 2020-12-31 04:51

    It is called as Qualified name lookup in C++.

    It means that the layer namespace being referred to is the one off the global namespace, rather than another nested namespace named layer.

    For Standerdese fans:
    $3.4.3/1

    "The name of a class or namespace member can be referred to after the :: scope resolution operator (5.1) applied to a nested-name-specifier that nominates its class or namespace. During the lookup for a name preceding the :: scope resolution operator, object, function, and enumerator names are ignored. If the name found is not a class-name (clause 9) or namespace-name (7.3.1), the program is ill-formed."

    0 讨论(0)
提交回复
热议问题