20

Is there a way to reuse the same enum value in separate types? I'd like to be able to something like the following:

enum DeviceState { UNKNOWN, ACTIVE, DISABLED, NOTPRESENT, UNPLUGGED };
enum DeviceType { UNKNOWN, PLAYBACK, RECORDING };

int _tmain(int argc, _TCHAR* argv[])
{
    DeviceState deviceState = DeviceState::UNKNOWN;
    DeviceType deviceType = DeviceType::UNKNOWN;
    return 0;
}

This makes sense to me, but not to the C++ compiler- it complains: error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator' on line 2 of the above. Is there a correct way of doing this, or am I supposed to always use unique enum values? I can't imagine this is always possible to guarantee if I'm including someone else's code.

2 Answers 2

30

For those using C++11, you may prefer to use:

enum class Foo

instead of just:

enum Foo

This provides similar syntax and benefits from as namespaces. In your case, the syntax would be:

enum class DeviceState { UNKNOWN, ACTIVE, DISABLED, NOTPRESENT, UNPLUGGED };
DeviceState deviceState = DeviceState::UNKNOWN;

Note that this is strongly typed so you will need to manually cast them to ints (or anything else).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, having to use the accepted answer of putting a named enum within a namespace would have been extremely ugly.
25

You can, and should, include your enums in a namespace:

namespace DeviceState
{
    enum DeviceState{ UNKNOWN, ACTIVE, DISABLED, NOTPRESENT, UNPLUGGED };
}
namespace DeviceType
{
    enum DeviceType{ UNKNOWN, PLAYBACK, RECORDING };
}

//...

DeviceType::DeviceType x = DeviceType::UNKNOWN;

5 Comments

Thanks Luchian. Please could you correct my example for me. I'm not sure how to declare a variable using namespaces as you describe above.
If I declare a variable as DeviceState deviceState = DeviceState::UNKNOWN;, I get a compiler error:'DeviceState' : illegal use of namespace identifier in expression
@IAmAI ok then you need to also name the enum.
Luchian - would you know why this is the way it is (or why the rules the way they are)? It seems silly to me to declare a separate namespace, especially for those who already have a namespace and place the enum within a class. I guess I fail to see what's ambiguous about DeviceState::UNKNOWN and DeviceType::UNKNOWN.
@noloader because you can address enum values without the enum qualifier. I.e. you could just write UNKNOWN, in which case it'd be ambiguous.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.