什么时候需要空命名空间定义?
命名空间的声明和定义与大多数其他事物不同,但与前向声明等效的命名空间是:
namespace X {} // empty body
通常,您可以通过在其中放置其他声明来定义命名空间。但是是否有一个问题,“命名空间前向声明”是最简单的解决方案?空命名空间有什么用?
Namespaces aren't declared and defined like most other things, but the namespace equivalent of a forward declaration would be:
namespace X {} // empty body
Normally, you define a namespace by placing other declarations inside it. But is there a problem for which this "namespace forward declaration" is the easiest solution? Of what use is an empty namespace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是甚至出现在标准中的一个: 声明一个 using 指令来表示命名空间
随后,您可以在其他时间打开命名空间并向其添加内容,并且 using 指令使这些内容对外部命名空间可见。
Here is one which even appears in the Standard: Declaring a using directive to denote a namespace
Afterwards you can open the namespace other times and add to it, and the using directive makes the stuff visible to the outer namespace.
我使用空命名空间定义来简化递归函数的声明,其中一侧是运算符重载。运算符被放置在它们自己的命名空间中,以允许根据需要在范围内选择性使用,而不是在标头包含在任何地方时强制使用(从而在解析变得不明确时强制错误)。
示例:
s << *begin 被延迟到 write_sequence 被实例化(因为它涉及模板参数),此时运算符已经被声明并且可以通过 using 指令找到。对于嵌套容器,该调用变得递归:
Boost 有一个类似的输出格式化库,但我不知道它们是否使用相同的实现技术。
I use an empty namespace definition to simplify declarations for recursive functions, where one "side" is operator overloads. The operators are placed in their own namespace to allow selective use in scopes as desired, rather than forcing use if the header is included anywhere (and thus forcing errors if resolutions become ambiguous).
Example:
The resolution of
s << *begin
is delayed until write_sequence is instantiated (because it involves template parameters), by which time the operator has been declared and can be found through the using directive. The call becomes recursive for nested containers:Boost has a similar output formatting library, but I don't know if they use the same implementation technique.