[英]What are some non-standard ways to use namespaces?
I am interested in unprecedented, cool, and esoteric ways to use namespaces.我对使用命名空间的前所未有的、酷炫的、深奥的方式很感兴趣。 I know that many advanced developers "hack" namespaces by, for example, using them as references to string constants.
我知道许多高级开发人员“破解”命名空间,例如,将它们用作对字符串常量的引用。 In the string constants example, the idea is to implement DRY (DRY = Do Not Repeat Yourself) and you can keep all your strings in one file.
在字符串常量示例中,想法是实现 DRY(DRY = Do Not Repeat Yourself)并且您可以将所有字符串保存在一个文件中。
note: I am looking for answers related to "common" languages such as C#, Ruby, Java, etc.注意:我正在寻找与“通用”语言(例如 C#、Ruby、Java 等)相关的答案。
One esoteric use I often resort to is when defining enums in C++, especially when there are several types in a cetain context.我经常使用的一种深奥的用法是在 C++ 中定义枚举时,尤其是在 cetain 上下文中有多种类型时。 This enables usage such as
Quality::k_high
and Importance::k_high
in related contexts.这可以在相关上下文中启用诸如
Quality::k_high
和Importance::k_high
。 Enums also often sport unknown values (usually to represent cases where none have been set), which need to be qualified to disambiguate constants (say, k_qualityNone
and k_importanceNone
), which is avoided using namespaces.枚举还经常使用未知值(通常表示没有设置的情况),需要有资格消除常量(例如
k_qualityNone
和k_importanceNone
),这是使用命名空间避免的。
A definition will thus look like:因此,定义将如下所示:
namespace Quality { enum Type { k_high, k_medium, k_low, k_none }; }
and和
namespace Importance { enum Type { k_high, k_medium, k_low, k_none }; }
Functions and methods will then take an argument of type Quality::Type
(and Importance::Type
), which is rather descriptive and nice.然后,函数和方法将采用
Quality::Type
(和Importance::Type
) Quality::Type
的参数,这相当具有描述性且很好。 Individual enumeration constants are also qualified similarly as mentioned earlier ( Quality::k_low
).单个枚举常量也有类似前面提到的限定(
Quality::k_low
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.