A group of variadic macros

前端 未结 2 2085
暗喜
暗喜 2021-01-19 03:56

I would like to have a group of variable number of arguments passed into a macro. I have following macros which is incorrect:

#define M_NARGS(...) M_NARGS_(_         


        
2条回答
  •  天命终不由人
    2021-01-19 04:14

    If you want to generate structs based on lists I would use higher order macros. This does not require you to have another macro that actually does the loop resolution.

    #define FRUITS(V) \
        V(apple) \
        V(banana) \
        V(cherry)
    
    #define ANIMALS(V) \
        V(dog) \
        V(monkey)
    
    #define VISIT_ANI_STRUCT(A) \
        Animal A;
    
    #define VISIT_FRU_STRUCT(F) \
        Fruit F;
    
    #define ZOO_BLOCK(NAME, GEN_ANI,GEN_FRU) \
        struct NAME ## Block { \
            ANIMALS(GEN_ANI) \
            FRUITS(GEN_FRU) \
        }
    
    ZOO_BLOCK(Zoo, VISIT_ANI_STRUCT, VISIT_FRU_STRUCT);
    

    Will result in:

    struct ZooBlock { Animal dog; Animal monkey; Fruit apple; Fruit banana; Fruit cherry; };
    

    Or if you need the other way round

    #define ZOO_BLOCK(NAME, A, F) \
        struct NAME ## Block { \
            A(VISIT_ANI_STRUCT) \
            F(VISIT_FRU_STRUCT) \
        }
    
    ZOO_BLOCK(Zoo, VISIT_ANI_STRUCT, VISIT_FRU_STRUCT);
    

提交回复
热议问题