Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put the "using namespace" inside or outside of a namespace in C++

Tags:

c++

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

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

rather than like this:

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

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

like image 478
Paul Wang Avatar asked Aug 16 '16 03:08

Paul Wang


1 Answers

In header file you should never have a using namespace N; directive in the global scope.

It will force lots of identifiers from N on all client code.

But it can be okay to have it inside a namespace X. Just keep in mind that client code that does using namespace X; will then also get all identifiers from N. A more conservative approach is to have a bunch of using declarations in namespace X, e.g. using N::foo;.


An alternative, when the reason for using namespace N; is that N is a very long name, like Not_short_enough_for_practical_use, is to use a namespace alias – preferably inside the smallest scope where it's needed:

namespace N = Not_short_enough_for_practical_use;

Your teacher's “correction” of moving a using namespace out of a namespace, before it, is of negative value.

You should always strive (within practical limits) to minimize the scope of anything.

like image 71
Cheers and hth. - Alf Avatar answered Nov 14 '22 23:11

Cheers and hth. - Alf