C++11 Fun with initializer lists, arrays, and enumerations

后端 未结 5 1770
天涯浪人
天涯浪人 2021-01-03 03:27

Background

C++11 initializer lists can be used to initialize vectors and arrays with argument passing to constructors.

I have a piece of code below

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 03:59

    The MACRO solution.

    #include 
    #include 
    
    #define COLORS(V,E) \
        V(RED) \
        V(GREEN) \
        E(BLUE)
    
    #define COMMA(V) \
        V,
    
    #define NCOMMA(V) \
        V
    
    #define SCOMMA(V) \
        #V,
    
    #define SNCOMMA(E) \
        #E
    
    enum Colors {
        COLORS(COMMA,NCOMMA)
    };
    
    const char * colors[] = {
        COLORS(SCOMMA,SNCOMMA)
    };
    
    #define INIT_LIST(V) \
        { V(COMMA,NCOMMA) }
    
    int main(int argc, char  **argv) {
        for ( auto i : INIT_LIST(COLORS) ) {
            printf("%s\n", colors[i]);
        }
    }
    

提交回复
热议问题