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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With