Paul Wang
Paul Wang

Reputation: 97

Should I put the "using namespace" inside or outside of a namespace in 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?

Upvotes: 6

Views: 1604

Answers (2)

Sergey
Sergey

Reputation: 8248

Your question looks somewhat opinion-based and depending on your company's internal policies.

You may have a very special case, but the common advise here is to declare every identifier as close to it's first use as possible. It will minimize scrolling and make your code easier to read. Also it will put identifiers in the smallest and the most nested namespace possible, preventing wider namespaces from being flooded with unnecessary identifiers.

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

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

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.

Upvotes: 11

Related Questions