namespaces for enum types - best practices

前端 未结 8 1915
隐瞒了意图╮
隐瞒了意图╮ 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 06:49

    Original C++03 answer:

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

    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

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

    If you're doing any of these practices, you are ahead of the curve and probably don't need to scrutinize this further.

    Newer, C++11 advice:

    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 discover ambiguous or buggy code.

提交回复
热议问题