Iterating over non-incremental Enum

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

    It is about tricky and more C than C++ practice, but you can use X macros. It is very ugly and you need to keep TABLE in right order. In C++ I believe we don't need to iterate over enumerations and more we don't need to assign values to enumeration (ostensibly enumeration value is random in every compilation). So think of it as a joke :)

    #include 
    
    #define CAPI_SUBTYPE_TABLE \
        CAPI_SUBTYPE_X(CAPI_SUBTYPE_NULL,     0 ) \
        CAPI_SUBTYPE_X(CAPI_SUBTYPE_DIAG_DFD, 1 ) \
        CAPI_SUBTYPE_X(CAPI_SUBTYPE_DD_ALL,   13)
    
    #define CAPI_SUBTYPE_X(name, value) name = value,
    enum CAPI_SUBTYPE
    {
        CAPI_SUBTYPE_TABLE
        CAPI_SUBTYPE_END
    };
    #undef CAPI_SUBTYPE_X
    
    #define CAPI_SUBTYPE_X(name, value) name,
    CAPI_SUBTYPE subtype_iteratable[] =
    {
        CAPI_SUBTYPE_TABLE
        CAPI_SUBTYPE_END
    };
    #undef CAPI_SUBTYPE_X
    
    #define CAPI_SUBTYPE_SIZE  (sizeof(subtype_iteratable) / sizeof(subtype_iteratable[0]) - 1)
    
    
    int main()
    {
        for (unsigned i = 0; i < CAPI_SUBTYPE_SIZE; ++i)
            std::cout << subtype_iteratable[i] << std::endl; // 0, 1, 13
    }
    

提交回复
热议问题