How solve compiler enum redeclaration conflict

Daniel Santos picture Daniel Santos · Dec 16, 2015 · Viewed 9k times · Source

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 conflicted the both UNKNOWN items and threw this error:

error: redeclaration of 'UNKNOWN'

I am able to solve this error changing one of the UNKNOWN to UNKNOWN_a, but I would like to do not change the names.

How can I solve this conflict without changing the enum items name?

Answer

NathanOliver picture NathanOliver · Dec 16, 2015

You can use scoped enumerations for this. This requires C++11 or higher support.

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;
}

Live Example