枚举类型的命名空间 - 最佳实践 [英] namespaces for enum types - best practices

查看:361
本文介绍了枚举类型的命名空间 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,需要几个枚举类型在一起。有时,有一个名字冲突。解决这个问题的两个解决方案:使用命名空间,或使用较大枚举元素名称。但是,命名空间解决方案有两个可能的实现:一个有嵌套枚举的虚拟类或一个完整的命名空间。

Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use 'larger' enum element names. Still, the namespace solution has two possible implementations: a dummy class with nested enum, or a full blown namespace.

我正在寻找所有三种方法的利弊。

I'm looking for pros and cons of all three approaches.

示例:

// oft seen hand-crafted name clash solution
enum eColors { cRed, cColorBlue, cGreen, cYellow, cColorsEnd };
enum eFeelings { cAngry, cFeelingBlue, cHappy, cFeelingsEnd };
void setPenColor( const eColors c ) {
    switch (c) {
        default: assert(false);
        break; case cRed: //...
        break; case cColorBlue: //...
        //...
    }
 }


// (ab)using a class as a namespace
class Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
class Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
    switch (c) {
        default: assert(false);
        break; case Colors::cRed: //...
        break; case Colors::cBlue: //...
        //...
    }
 }


 // a real namespace?
 namespace Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
 namespace Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
 void setPenColor( const Colors::e c ) {
    switch (c) {
        default: assert(false);
        break; case Colors::cRed: //...
        break; case Colors::cBlue: //...
        //...
    }
  }


推荐答案

来自命名空间的益处 $ c> class )是您可以使用使用声明。

The benefit from a namespace (over a class) is that you can use using declarations when you want.

使用命名空间问题是可以在代码中的其他位置扩展命名空间。在一个大项目中,你不能保证两个不同的枚举不会同时认为它们被称为 eFeelings

The problem with using a namespace is that namespaces can be expanded elsewhere in the code. In a large project, you would not be guaranteed that two distinct enums don't both think they are called eFeelings

对于更简单的代码,我使用 struct ,因为你想要的内容是公开的。

For simpler-looking code, I use a struct, as you presumably want the contents to be public.

附录如果您正在进行上述任何操作,

Addendum

如果您使用的是C ++ 11或更高版本,枚举类将隐式地枚举enum中的枚举值

If you are using C++11 or later, enum class will implicitly scope the enum values within the enum's name.

使用枚举类,您将丢失隐式转换和与整数类型的比较,你标记模糊的或有错误的代码。

With enum class you will lose implicit conversions and comparisons to integer types, but in practice that may help you flag ambiguous or buggy code.

这篇关于枚举类型的命名空间 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆