5

I was integrating some C++ in somelse's one and found out we adopt two different strategies regarding the use of using namespace commands.

For cleanliness of source code, which of the two is the most correct solution?

namespace foo
{
   using namespace bar;
}

or

using namespace bar;

namespace foo
{
}

Thanks a lot for your help,

T.

Tambo
  • 93
  • 4

2 Answers2

7

The two are not equivalent. In the first case the namespace bar is imported in the namespace foo so for every bar::x you can access it as foo::x. In the latter the namespace bar is imported in the global namespace (or the namespace that wraps both up) and it can be accessed as ::x.

I'd recommend to always choose the narrowest possible solution for you. Even to the point of including the namespace only in the function you actually need it. So if you are in doubt go with the first one.

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 1
    +1 for "narrowest possible". I almost never write `using namespace` - it's almost always better to use only the specific names you want from the namespace. – Toby Speight Oct 19 '15 at 16:48
  • @TobySpeight Sure. Exceptions to this are namespaces like `std::literals` or `std::placeholders` which are designed to be included in its entirety. – Shoe Oct 19 '15 at 16:49
  • @Jefffrey agreed, although because boost got there first, even std::placeholders can be a minefield. std::literals is about the only safe one. – Richard Hodges Oct 19 '15 at 16:59
0

This question is already answered, but I want to reiterate the point mooted by Toby Speight. One should never write something like using namespace bar.

Good practice is to use using as a aliasing aid for long/hierarchial namespaces. Like

using po = boost::program_options;

And then use

po.notify(vm);

Either of two alternatives suggested in question are only good for discussions or interviews.

g-217
  • 2,069
  • 18
  • 33
  • "One should never write something like `using namespace bar`". I disagree entirely. Certain namespaces are meant to be imported with `using namespace`. Just like pretty much any other absolute you can stick to programming, there are always exceptions. – Shoe Oct 19 '15 at 17:23
  • I am reiterating the point discussed in http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – g-217 Oct 19 '15 at 17:28
  • My question is not answered in that discussion. I was asking about the best practice among the 2, not whether one of them was to consider as a bad one – Tambo Oct 21 '15 at 13:39
  • "I'd recommend to always choose the narrowest possible solution for you" -- clearly says first option is better, if you really need to import a namespace. – g-217 Oct 22 '15 at 14:46