Iterating over non-incremental Enum

前端 未结 15 2024
长发绾君心
长发绾君心 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:04

    Use Higher Order macros

    Here's the technique we've been using in our projects.

    Concept:

    The idea is to generate a macro called LISTING which contains the definition of name-value pairs and it takes another macro as an argument. In the example below I defined two such helper macros. 'GENERATE_ENUM' to generate the enum and 'GENERATE_ARRAY' to generate an iteratable array. Of course this can be extended as necessary. I think this solution gives you the most bang for the buck. Conceptually it's very similar to iammilind's solution.

    Example:

    // helper macros
    #define GENERATE_ENUM(key,value)       \
          key = value                      \
    
    #define GENERATE_ARRAY(name,value)     \
           name                            \
    
    // Since this is C++, I took the liberty to wrap everthing in a namespace. 
    // This done mostly for aesthetic reasons, you don't have to if you don't want.        
    namespace CAPI_SUBTYPES 
    {
        //  I define a macro containing the key value pairs
        #define LISTING(m)                 \ 
           m(NONE, 0),    /* Note: I can't use NULL here because it conflicts */
           m(DIAG_DFD, 1),                 \
           m(DIAG_ERD, 2),                 \
           ...
           m(DD_ALL, 13),                  \
           m(DD_COUPLE, 14),               \
           ...
                   m(DIAG_SAD, 51),                \
           m(DIAG_ASG, 59),                \
    
        typedef enum {
           LISTING(GENERATE_ENUM)
        } Enum;
    
        const Enum At[] = {
           LISTING(GENERATE_ARRAY)
        };
    
        const unsigned int Count = sizeof(At)/sizeof(At[0]);
    }
    

    Usage:

    Now in code you can refer to the enum like this:

    CAPI_SUBTYPES::Enum eVariable = CAPI_SUBTYPES::DIAG_STD;
    

    You can iterate over the enumeration like this:

    for (unsigned int i=0; i

    Note:

    If memory serves me right, C++11 enums live in their own namespaces (like in Java or C#) , therefore the above usage wouldn't work. You'd have to refer to the enum values like this CAPI_SUBTYPES::Enum::FooBar.

提交回复
热议问题