23

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

using namespace ::layer::module;

and

using namespace layer::module;

What causes the additional :: before layer?

spraff
  • 32,570
  • 22
  • 121
  • 229
Dudero
  • 607
  • 7
  • 15
  • 2
    This is a repeat of http://stackoverflow.com/q/4925394/498253 – Tom Jul 22 '11 at 12:43
  • @Tom: But is this indeed an exact dupe? – sbi Jul 22 '11 at 12:47
  • 1
    @sbi: Yep, 'what the prepending :: mean - and why is it used?' but since there are more answers here than there I woudn't close - I just thought the link would be helpful – Tom Jul 22 '11 at 12:51

4 Answers4

30

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.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
22

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();
  }
}
sbi
  • 219,715
  • 46
  • 258
  • 445
17

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".

spraff
  • 32,570
  • 22
  • 121
  • 229
6

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."

Alok Save
  • 202,538
  • 53
  • 430
  • 533