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
?
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
The using namespace statement just means that in the scope it is present, make all the things under the std namespace available without having to prefix std:: before each of them.
Namespace in C++ is the declarative part where the scope of identifiers like functions, the name of types, classes, variables, etc., are declared. The code generally has multiple libraries, and the namespace helps in avoiding the ambiguity that may occur when two identifiers have the same name.
C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With