仅在一个特定类文件中使用命名空间

Using a namespace only inside one specific class file

本文关键字:文件 命名空间 一个      更新时间:2023-10-16

或多或少考虑到语法语义,这是一个相当简单的问题。

我在一个命名空间中有一个类,它使用了另一个命名空间之外的许多类:

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

这个类当然在它自己的.hpp文件中。

我想让名称空间"anothernamespace"中的所有内容都可用于MyClass类,但是,如果我简单地这样说的话:

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

任何做的人

using namespace SomeNamespace;

还会自动使用另一个名称空间——这是我想要避免的。

我如何实现我想要的?

最简单但有帮助的解决方案是使用名称空间别名:

namespace SomeNamespace
{
   namespace ans = anothernamespace; // namespace alias
   class MyClass
   {
      //...
      //These types of namespace uses occur alot around here:
      void DoSomething(const ans::anotherclass &arg);
      //...
   }
}

您的类用户不会"使用namespace anothernamespace;",这样会更安全,但您仍然必须在类中使用别名。不确定这是否有帮助,这取决于你是想少打字还是隐藏一个类型。在这里,您将完整的名称空间放在一种子名称空间中,该子名称空间不会进入用户的名称空间,但仍然可用。

否则。。。没有办法做你想做的事。使用命名空间在类声明中不起作用。

这可以满足您的需要。MyClass可以访问这两个命名空间。不过,using namespace在标头中是不好的做法。

namespace SomeNamespace {
namespace other {
  using namespace anothernamespace;
  class MyClass {
  };
}}
namespace SomeNamepace {
  typedef other::MyClass MyClass;
}

您确实应该更喜欢在类声明中指定另一个名称空间:。

你不能。恐怕就这么简单。