为什么我不能把“使用”放在类声明中的声明?
我了解当您将 using
声明放入头文件中时可能会遇到的麻烦,所以我不想这样做。相反,我尝试将 using
(或 namespace foo =
)放在类声明中,以减少头文件中的重复键入。不幸的是我遇到编译器错误。看起来这将是一个有用的功能。
#ifndef FOO_H
#define FOO_H
// This include defines types in namespace gee::whiz::abc::def,
// such as the class Hello.
#include "file_from_another_namespace.h"
// using namespace gee::whiz::abc::def; // BAD!
namespace x {
namespace y {
namespace z {
struct Foo {
using namespace gee::whiz::abc::def; // Illegal.
namespace other = gee::whiz::abc::def; // Illegal.
// Foo(gee::whiz::abc::def::Hello &hello); // annoyingly long-winded
Foo(other::Hello &hello); // better
//...
};
} } } // end x::y::z namespace
#endif // FOO_H
在真实的代码中,命名空间名称更长且烦人,这不是我可以更改的。
谁能解释为什么这不合法,或者(更好)是否有解决方法?
I understand the troubles you can get into when you put a using
declaration inside a header file, so I don't want to do that. Instead I tried to put the using
(or a namespace foo =
) within the class declaration, to cut down on repetitive typing within the header file. Unfortunately I get compiler errors. Seems like it would be a useful feature.
#ifndef FOO_H
#define FOO_H
// This include defines types in namespace gee::whiz::abc::def,
// such as the class Hello.
#include "file_from_another_namespace.h"
// using namespace gee::whiz::abc::def; // BAD!
namespace x {
namespace y {
namespace z {
struct Foo {
using namespace gee::whiz::abc::def; // Illegal.
namespace other = gee::whiz::abc::def; // Illegal.
// Foo(gee::whiz::abc::def::Hello &hello); // annoyingly long-winded
Foo(other::Hello &hello); // better
//...
};
} } } // end x::y::z namespace
#endif // FOO_H
In the real code, the namespace names are much longer and annoying and it's not something I can change.
Can anyone explain why this is not legal, or (better) if there's a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你能做
typedef gee::whiz::abc::def::Hello Hello
吗?Could you do
typedef gee::whiz::abc::def::Hello Hello
?实际上这并不是一个完全可怕的想法。它至少和现在的工作方式一样有意义(当然,意义不大)。我认为基本问题是类不是编译和链接的单位,而是“翻译单位”。但是逐个类地执行要干净得多,让类成为模块,就像在 Java 或 C# 或其他更有意义的语言中一样。
actually not a totally horrid idea. It makes at least as much sense as how it works now (which granted, isn't much). I think the basic problem is that classes are not the unit of compilation and linking, but 'translation units'. But doing it class by class is much cleaner, having classes be modules, like in Java or C# or other languages that make more sense.
遇到同样的问题,发现了这个问题。我发现如果你用匿名命名空间包装 struct foo ,似乎你
也可以使用 using namespace::many::names;
在匿名包装的顶部。不过,添加更多层嵌套大括号有点丑陋。
Had the same problem, found this question. I figured out that if you wrap struct foo with an anonymous namespace, it seems you can put
using namespace too::many::names;
at the top of the anonymous wrapper. It's kind of ugly, though, adding more layers of nested braces.