Should I put "use namespace" inside or outside the namespace in C ++

My mentor changed my code like this in a code review:

using namespace A; // defined in other files namespace B{ // do something } 

not like that:

 namespace B{ using namespace A; // do something } 

Is there any technical reason for placing the using namespace outside the namespace?

+5
source share
2 answers

The header file should never contain directives using namespace N; in a global area.

It will force many identifiers from N to all client code.

But this may be good if it is inside the X namespace. Just keep in mind that the client code that is using namespace X; , will also receive all identifiers from N A more conservative approach is to have a bunch of using declarations in the X namespace, for example. using N::foo; .


An alternative is when the reason for using namespace N; is that N is a very long name, for example Not_short_enough_for_practical_use , is to use a namespace alias - preferably in the smallest amount where necessary:

 namespace N = Not_short_enough_for_practical_use; 

Your teacher "corrects" moving a using namespace from the namespace before it has a negative value.

You should always strive (within practical limits) to minimize the volume of everything.

+10
source

Your question looks somewhat based on opinions and depends on the internal policy of your company.

You may have a very special case, but the general advice here is to declare each identifier as close to it as possible. This will minimize scrolling and simplify code reading. In addition, it will put identifiers in the smallest and most nested namespace, which will prevent the wider namespaces from being flooded with unnecessary identifiers.

So, if I were you, I would demand from your mentor reasonable explanations about the change that he proposed.

+1
source

All Articles