Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of "using" in header files

I understood, that I should not use this in a header file:

using namespace foo;

Because it brings the namespace foo in the global scope for anyone who uses my header file.

Can I prevent this from happening, if I do it in my own namespace? For example like this:

namespace my_lib
{
    using namespace foo;

    // my stuff
    // ...
}

Now the using namespace foo should be restricted to the scope of the namespace my_lib, right?

like image 793
DyingSoul Avatar asked May 03 '11 11:05

DyingSoul


2 Answers

Yes. That is better than using using namespace foo at global level.

Yet better would be if you use foo::name syntax.

Now the using namespace foo should be restricted to the scope of the namespace my_lib, right?

Yes. It brings all the names from the namespace foo in the namespace my_lib which might cause name collisions in my_lib. That is why foo::name is the most preferrable approach.

like image 180
Nawaz Avatar answered Sep 18 '22 11:09

Nawaz


Yes, if you do that then it just brings all the names from foo into my_lib -- which, as others have pointed out, may or may not be desirable.

One thing I would observe in addition to what others have said is that you can use the 'using directive within a namespace' idea as a way of simulating a using directive that is restricted to class scope. Note that this is illegal:

class C
{
  using namespace boost; // for example

  // ...
};

But you can do this instead:

namespace C_Namespace {
  using namespace boost;

  class C
  {
  };
}

using C_Namespace::C; // bring C itself back into the global namespace

Just thought you might find it useful if what you really want is to be able to define something (like a class) without writing a particular namespace prefix the whole time.

like image 22
Stuart Golodetz Avatar answered Sep 18 '22 11:09

Stuart Golodetz