Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How solve compiler enum redeclaration 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 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?

like image 303
Daniel Santos Avatar asked Dec 16 '15 18:12

Daniel Santos


3 Answers

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

like image 121
NathanOliver Avatar answered Nov 10 '22 21:11

NathanOliver


Use scoped enums (C++ 11) - enum classes. They will not pollute the outer scope with duplicate names.

But, you'll need to access the enumerated values with a scope resolution operator - Identity::UNKNOWN, which is not a bad thing.

like image 7
LogicStuff Avatar answered Nov 10 '22 19:11

LogicStuff


If using C++11 is not feasible(It really should by now, I mean, it's 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, enum class is much better.

like image 5
Cássio Renan Avatar answered Nov 10 '22 20:11

Cássio Renan