Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing enum values in separate enum types

Tags:

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.

like image 228
Dan Stevens Avatar asked May 02 '12 09:05

Dan Stevens


People also ask

Can two different enums have the same value?

1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can enum have another enum?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can you loop through enums?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can we have enum inside enum in C?

It is not possible to have enum of enums, but you could represent your data by having the type and cause separately either as part of a struct or allocating certain bits for each of the fields.


1 Answers

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).

like image 135
Rick Smith Avatar answered Sep 29 '22 17:09

Rick Smith