namespaces for enum types - best practices

前端 未结 8 1837
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 06:34

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 na

相关标签:
8条回答
  • 2020-12-04 07:01

    An difference between using a class or a namespace is that the class cannot be reopened like a namespace can. This avoids the possibility that the namespace might be abused in the future, but there is also the problem that you cannot add to the set of enumerations either.

    A possible benefit for using a class, is that they can be used as template type arguments, which is not the case for namespaces:

    class Colors {
    public:
      enum TYPE {
        Red,
        Green,
        Blue
      };
    };
    
    template <typename T> void foo (T t) {
      typedef typename T::TYPE EnumType;
      // ...
    }
    

    Personally, I'm not a fan of using, and I prefer the fully qualified names, so I don't really see that as a plus for namespaces. However, this is probably not the most important decision that you'll make in your project!

    0 讨论(0)
  • 2020-12-04 07:06

    FYI In C++0x there is a new syntax for cases like what you mentioned (see C++0x wiki page)

    enum class eColors { ... };
    enum class eFeelings { ... };
    
    0 讨论(0)
提交回复
热议问题