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
?
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.
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();
}
}
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".
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."
精彩评论