Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a namespace only inside one specific class file

Tags:

c++

using

This is a rather simple question more or less considering syntax semantics.

I've got a class inside a namespace, which uses a lot of classes out of another namespace:

namespace SomeNamespace
{
   class MyClass
   {
      //...

      //These types of namespace uses occur alot around here:
      void DoSomething(const anothernamespace::anotherclass &arg);
      //...
   }
}

This class is of course in its own .hpp file.

I would like to make everything inside the namespace "anothernamespace" available to the MyClass class, however, if I simply put it like this:

namespace SomeNamespace
{
   using namespace anothernamespace;
   class MyClass
   {
      //...

      //These types of namespace uses occur alot around here:
      void DoSomething(const anothernamespace::anotherclass &arg);
      //...
   }
}

Anyone who does

using namespace SomeNamespace;

Will automatically also use anothernamespace - which is what I want to avoid.

How do I achieve what I want?

like image 537
TravisG Avatar asked Sep 16 '25 11:09

TravisG


2 Answers

The simplest non-perfect-but-helping solution would be to use a namespace alias :

namespace SomeNamespace
{
   namespace ans = anothernamespace; // namespace alias
   class MyClass
   {
      //...

      //These types of namespace uses occur alot around here:
      void DoSomething(const ans::anotherclass &arg);
      //...
   }
}

Your class users will not "using namespace anothernamespace;", making it more safe, but you still have to use the alias in your class. Not sure it helps, it depends on if you just want to type less or maybe hide a type. Here you put the full namespace in a kind of sub-namespace that don't get into the user's namespaces, but is still available.

Otherwise... there is no way to do exactly what you want. Using namespace don't work inside class declarations.

like image 59
Klaim Avatar answered Sep 18 '25 10:09

Klaim


This does what you want. Both namespaces are accessible to MyClass. using namespace is bad practice in headers though.

namespace SomeNamespace {
namespace other {
  using namespace anothernamespace;
  class MyClass {
  };
}}

namespace SomeNamepace {
  typedef other::MyClass MyClass;
}

You really should prefer specifying anothernamespace:: in your class declaration.

like image 25
Tom Kerr Avatar answered Sep 18 '25 11:09

Tom Kerr