仅在一个特定类文件中使用命名空间
Using a namespace only inside one specific class file
或多或少考虑到语法语义,这是一个相当简单的问题。
我在一个命名空间中有一个类,它使用了另一个命名空间之外的许多类:
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;
}
您确实应该更喜欢在类声明中指定另一个名称空间:。
你不能。恐怕就这么简单。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 使用 Clang++ 有没有办法将文件作为命名空间等包含?
- Qt C++:不同文件中同一命名空间的多个Q_NAMESPACE
- 不同C++文件中未命名命名空间中的名称可以引用同一个命名事物吗?
- 使用命名空间在另一个".cpp"文件中定义
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 是否将命名空间范围文件本地 (.cpp) 常量放在匿名命名空间中
- 模板实现文件中的匿名命名空间
- C++-使用来自不同头文件、相同命名空间的枚举
- C++ 如何在 def 文件中指定命名空间
- 在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?
- 在头文件中添加命名空间函数
- 在多个 cpp 文件中重用未命名的命名空间函数
- 使用匿名命名空间中的函数或另一个文件中的静态函数不应该出错吗?
- 跨命名空间的友元类和不同的.H 文件
- 我可以在应用程序之间更改 .proto 文件的命名空间吗?
- 试图将两个类放在同一命名空间中的单独文件中,但只有#1个#Class类作品
- C++中的头文件和命名空间
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?
- 包含所有命名空间 std 的文件