the syntax:
using namespace x;
tells the compiler to find the symbols from namespace x. The situation becomes bad once you have a same symbol in two namespaces and you want to mutually use them. Is there a way to tell the compiler not to use a namespace? What I mean is something like this (namespaces x and y both have the function a)
using namespace x;
int k = a(); //x::a is called
drop namespace x; //imaginary syntax that I am looking for
using namespace y;
int j = a(); //y::a is called
"You must use scope resolution symbol '::'" is not the answer I am looking for.
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.
Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it.
The problem with putting using namespace in the header files of your classes is that it forces anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.
Since you don't want to use scope resolution, then create some additional scope:
{
using namespace x;
int k = a(); //x::a is called
}
{
using namespace y;
int j = a(); //y::a is called
}
I'm afraid this might turn to be worse than scope resolution, though :/
Edit:
One more thing (which I don't know if you're aware of) that might be helpful are namespace aliases. Say you've got a namespace with a disgustingly long name or multiple nested namespaces. You can shorten the name such as:
namespace x = very::weird::namespc::name;
namespace y = yabadabadoopdiedoo;
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