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
}
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46
  • 5
    This is not an issue, it's intentional, and useful. – Jonathan Wakely Aug 19 '15 at 10:50
  • 6
    @JonathanWakely There is an issue here: sometimes, you do want a way to prevent/detect duplicates. Other times you don't. The lack of a way to easily detect it is an issue; the lack of it preventing duplicates is not an issue, and not asked for in the question. This issue should be solved if/when the reflection working group gets their work into a standard... – Yakk - Adam Nevraumont Aug 20 '15 at 14:13
  • duplicates: [C/C++ enums: Detect when multiple items map to same value](https://stackoverflow.com/q/2576868/995714), [c++: ensure enum values are unique at compile time](https://stackoverflow.com/q/21378938/995714) – phuclv Apr 15 '20 at 01:10
  • Does this answer your question? [C/C++ enums: Detect when multiple items map to same value](https://stackoverflow.com/questions/2576868/c-c-enums-detect-when-multiple-items-map-to-same-value) – phuclv Apr 15 '20 at 01:11
  • the solution is to use the Boost Preprocessor library, or write a switch – phuclv Apr 15 '20 at 01:11

1 Answers1

5

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524