重命名 C++ 中的类
我想在头文件中引用一个类,该类位于一长串嵌套命名空间中:MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass
。我想以不同的名称使用它,但不是 MyVeryLongNamedClass
- 更短且更有用的名称,例如 MyClass
。
我可以将 using MySpaceA::MySpaceB::MySpaceC::MySpaceD
放在我的标头中,但我不想导入整个命名空间。我更喜欢某种结构,例如
using MyClass = MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass
我知道这对于命名空间是可能的,但我似乎无法做到这一点与班级一起工作。
非常感谢您的帮助。
I have a class that I would like to reference in my header file, which is in a long chain of nested namespaces: MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass
. I would like to use it under a different name, but not MyVeryLongNamedClass
-- something shorter and more useful, like MyClass
.
I could put using MySpaceA::MySpaceB::MySpaceC::MySpaceD
in my header, but I do not want to import the whole namespace. I would prefer to have some kind of construction like
using MyClass = MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass
I know this is possible with name spaces, but I cannot seem to get it to work with classes.
Thank you very much for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
using 不能用于给类起别名 - 为此你需要 typedef。您真的需要那些嵌套的命名空间吗? C++ 的命名空间功能从来没有打算成为一种架构机制 - 它只是为了防止名称冲突。如果您没有冲突(大多数情况下没有冲突),请不要使用它!
Using cannot be used to alias classes - for that you need typedef. And do you really need those nested namespaces? The namespace feature of C++ was never intended to be an architectural mechanism - it was simply there to prevent name clashes. If you don't have clashes, which mostly you don't, don't use it!
这似乎对我有用
现在你可以这样做
This seems to work for me
Now you can just do
引入“...MySpaceD”命名空间
仅将“..MyVeryLongNamedClass”类引入您的命名空间。
你可以用 typedef 给它“别名”:
建议阅读
第 57 章
(停止命名空间污染!熄掉你的香烟!)
Brings in the '...MySpaceD' namespace
Only brings in the '..MyVeryLongNamedClass' class into your namespace.
You can 'alias' it with a typedef:
Suggested Reading
Chapter 57
(stop namespace polution! Put out your cigarette!)
对于模板,您可以使用 模板 typedef:
现在您可以参考 < code>MyClass::type 而不是
MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass
。For templates, you could use a template typedef:
Now you can refer to
MyClass<T>::type
instead ofMySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass<T>
.