Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I undo the effect of "using namespace" in C++?

With using namespace I make the whole contents of that namespace directly visible without using the namespace qualifier. This can cause problems if using namespace occurs in widely used headers - we can unintendedly make two namespaces with identical classes names visible and the compiler will refuse to compile unless the class name is prepended with the namespace qualifier.

Can I undo using namespace so that the compiler forgets that it saw it previously?

like image 452
sharptooth Avatar asked Jan 28 '10 07:01

sharptooth


People also ask

How do I turn off namespace?

No you can't unuse a namespace. The only thing you can do is putting the using namespace -statement a block to limit it's scope.

What happens if you remove using namespace std from your code?

Thus, removing using namespace std; changes the meaning of those unqualified names, rather than just making the code fail to compile. These might be names from your code; or perhaps they are C library functions.

Why should we avoid use of using namespace in header files?

You should definitely NOT use using namespace in headers for precisely the reason you say, that it can unexpectedly change the meaning of code in any other files that include that header. There's no way to undo a using namespace which is another reason it's so dangerous.

Does using namespace std affect performance?

It doesn't affect the runtime performance at all.


2 Answers

No, but you can tell your coworkers that you should never have a using directive or declaration in a header.

like image 168
rlbond Avatar answered Oct 16 '22 13:10

rlbond


As others said, you can't and the problem shouldn't be there in the first place.
The next-best thing you can do is bring in your needed symbols so that they are preferred by the name look-up:

namespace A { class C {}; } namespace B { class C {}; } using namespace A; using namespace B;  namespace D {     using A::C; // fixes ambiguity     C c; } 

In some cases you can also wrap the offending includes with a namespace:

namespace offender { #  include "offender.h" } 
like image 26
Georg Fritzsche Avatar answered Oct 16 '22 14:10

Georg Fritzsche