Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Enum class containing duplicate values

Tags:

c++

c++11

The classic C++ enums don't have a straight forward method to detect duplicate values.

Is this issue addressed in the new C++11 enum class?

enum class ConnectionState : uint32_t
{
    Connecting,
    Reconnecting = 2,
    Disconnecting,
    LocalConnection,
    NoNetwork = 2,
    WifiNetwork,
    Last
}
like image 740
Alexandru Irimiea Avatar asked Aug 19 '15 10:08

Alexandru Irimiea


1 Answers

There is currently no way to detect or prevent multiple identical enum values in an enum.

The reflection working group is working on how to add reflection -- the ability for C++ code to introspect C++ code -- to the language. In the long list of stuff that reflection covers, there is a short list being worked on, and in that short list, examining the values of an enumeration at compile time is there.

N4428 contains a proposal for enum reflection. There are some partial implementations out there.

Under N4428, detecting duplicates would be easy. You can get the number of enumeration values, and their value, all at compile time. Simply create a pack of all the enum values in order, and test that they are unique. Then toss the result of that test into a static_assert.

The end result could be:

template<class E>
constexpr bool all_values_unique(); // todo

static_assert( all_values_unique<ConnectionState>(), "Duplicate enum value detected" );

Prior to something like that reflection proposal being added to C++, this is not possible.

You can fake it using macros -- have a macro that both creates your enum and creates reflection traits information about it -- then write all_values_unique that uses the reflection traits information. This has the advantage that if/when the standard and/or your compiler gets the reflection features needed, it may be easy to strip out your macros.

like image 191
Yakk - Adam Nevraumont Avatar answered Oct 19 '22 01:10

Yakk - Adam Nevraumont