A group of variadic macros

萝らか妹 提交于 2019-12-01 19:05:40

I'm not sure whether this is what you are looking for, but the parenthesised fruit and animal groups are not resolved. You can "flatten" them with your M_IDmacro, e.g.:

#define M_ID(...) __VA_ARGS__

#define FRUITS M_ID(apple, banana, cherry)
#define ANIMALS M_ID(dog, monkey)

#define ZOO_BLOCK(NAME, FRTS, ANMLS) struct NAME##Block {   \
  M_FOR_EACH(DEFINE_FRUITS, FRTS)                           \
  M_FOR_EACH(DEFINE_ANIMALS, ANMLS)                          \
}

#define DEFINE_FRUITS(F) Fruit F;
#define DEFINE_ANIMALS(F) Animal F;

ZOO_BLOCK(MyZoo, FRUITS, ANIMALS);

This, together with correcting a minor typo in DEFINE_ANIMAL/S yields:

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!