How to resolve compiler reflow conflict

Consider the following C ++ enumerations:

enum Identity { UNKNOWN = 1, CHECKED = 2, UNCHECKED = 3 }; enum Status { UNKNOWN = 0, PENDING = 1, APPROVED = 2, UNAPPROVED = 3 }; 

The compiler ran into two UNKNOWN tags and threw this error:

error: re-writing "UNKNOWN"

I can solve this error by changing one of UNKNOWN to UNKNOWN_a , but I would not want to change the names.

How can I resolve this conflict without changing the name of the enum element?

+6
source share
4 answers

You can use scoped listings for this. This requires support for C ++ 11 or later.

 enum class Identity { UNKNOWN = 1, CHECKED = 2, UNCHECKED =3 }; enum class Status { UNKNOWN = 0, PENDING = 1, APPROVED = 2, UNAPPROVED =3 }; int main () { Identity::UNKNOWN; Status::UNKNOW; } 

Living example

+13
source

Use enum scope (C ++ 11) - enum class es. They will not pollute external coverage with duplicate names.

But you will need to access the listed values ​​using the scope resolution operator - Identity::UNKNOWN , which is not so bad.

+4
source

If using C ++ 11 is not possible (actually it should be now, I mean, this is already 2015), consider using namespaces:

 namespace Identity { enum { UNKNOWN = 1, CHECKED = 2, UNCHECKED =3 }; } namespace Status { enum { UNKNOWN = 0, PENDING = 1, APPROVED = 2, UNAPPROVED =3 }; } 

But, really, the enum class much better.

+3
source

This is how I usually declare such enumerations (unless I need something more unusual, such as automatically converting enumeration names to strings, serialization / deserialization, etc.):

 struct Identities { enum Type { UNKNOWN = 1, CHECKED = 2, UNCHECKED = 3 }; }; typedef Identities::Type Identity; struct States { enum Type { UNKNOWN = 0, PENDING = 1, APPROVED = 2, UNAPPROVED = 3 }; }; typedef States::Type Status; // usage Identity identity = Identities::UNKNOWN; Status status = States::UNKNOWN; 

It works in every version of C ++ and is also type safe. Namespaces can also be used instead of structs (but I usually use structs).

+2
source

All Articles