Detect when multiple enum items map to same value

后端 未结 8 2162
猫巷女王i
猫巷女王i 2020-11-28 13:44

Is there a compile-time way to detect / prevent duplicate values within a C/C++ enumeration?

The catch is that there are multiple items which are initialize

8条回答
  •  情歌与酒
    2020-11-28 13:50

    I didn't completely like any of the answers already posted here, but they gave me some ideas. The crucial technique is to rely on Ben Voight's answer of using a switch statement. If multiple cases in a switch share the same number, you'll get a compile error.

    Most usefully to both myself and probably the original poster, this doesn't require any C++ features.

    To clean things up, I used aaronps's answer at How can I avoid repeating myself when creating a C++ enum and a dependent data structure?

    First, define this in some header someplace:

    #define DEFINE_ENUM_VALUE(name, value)      name=value,
    #define CHECK_ENUM_VALUE(name, value)       case name:
    #define DEFINE_ENUM(enum_name, enum_values) \
        typedef enum { enum_values(DEFINE_ENUM_VALUE) } enum_name;
    #define CHECK_ENUM(enum_name, enum_values) \
        void enum_name ## _test (void) { switch(0) { enum_values(CHECK_ENUM_VALUE); } }
    

    Now, whenever you need to have an enumeration:

    #define COLOR_VALUES(GEN) \
        GEN(Red, 1) \
        GEN(Green, 2) \
        GEN(Blue, 2)
    

    Finally, these lines are required to actually make the enumeration:

    DEFINE_ENUM(Color, COLOR_VALUES)
    CHECK_ENUM(Color, COLOR_VALUES)
    

    DEFINE_ENUM makes the enum data type itself. CHECK_ENUM makes a test function that switches on all the enum values. The compiler will crash when compiling CHECK_ENUM if you have duplicates.

提交回复
热议问题