Iterating over non-incremental Enum

前端 未结 15 1731
长发绾君心
长发绾君心 2021-01-31 15:42

Before you ask, I\'ve looked and looked for this on SO, and cannot find a solid answer.

I need to be able to dynamically iterate over an enum that has non-incre

15条回答
  •  时光取名叫无心
    2021-01-31 16:19

    With C++, the only way to iterate through enums is store them in an array and iterate through the same. The main challenge is how to track the same order in the enum declaration and the array declaration?
    You can automate the way you order them in the enum as well as array. I feel that this is a decent way:

    // CAPI_SUBTYPE_E_list.h
    // This header file contains all the enum in the order
    // Whatever order is set will be followed everywhere
    NAME_VALUE(CAPI_SUBTYPE_NULL, 0),         /* Null subtype. */
    NAME_VALUE(CAPI_SUBTYPE_DIAG_DFD, 1),     /* Data Flow diag. */
    NAME_VALUE(CAPI_SUBTYPE_DIAG_ERD, 2),     /* Entity-Relationship diag. */
    ...
    NAME_VALUE(CAPI_SUBTYPE_DD_ALL, 13),      /* DD Entries (All). */
    NAME_VALUE(CAPI_SUBTYPE_DD_COUPLE, 14),   /* DD Entries (Couples). */
    ...
    NAME_VALUE(CAPI_SUBTYPE_DIAG_ASG, 59)     /* ASG diagram. */
    

    Now you #include this file in your enum declaration and array declaration both places with macro redefinition:

    // Enum.h
    typedef enum {
    #define NAME_VALUE(NAME,VALUE) NAME = VALUE
    #include"CAPI_SUBTYPE_E_list.h"
    #undef NAME_VALUE
    }CAPI_SUBTYPE_E;
    

    And put the same file for array with other macro definition:

    // array file
    // Either this array can be declared `static` or inside unnamed `namespace` to make 
    // ... it visible through a header file; Or it should be declared `extern` and keep ...
    // ...  the record of its size; declare a getter method for both array and the size
    unsigned int CAPI_SUBTYPE_E_Array [] = {
    #define NAME_VALUE(NAME,VALUE) NAME
    #include"CAPI_SUBTYPE_E_list.h"
    #undef NAME_VALUE
    };
    

    Now iterate in C++03 as:

    for(unsigned int i = 0, size = sizeof(CAPI_SUBTYPE_E_Array)/sizeof(CAPI_SUBTYPE_E_Array[0]);
        i < size; ++i)
    

    or yet simple in C++11:

    for(auto i : CAPI_SUBTYPE_E_Array)
    

提交回复
热议问题