问题描述
我想有一组传递给宏参数变量数目。我有以下宏这是不正确的:
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_(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define M_NARGS_(_10, _9, _8, _7, _6, _5, _4, _3, _2, _1, N, ...) N
#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define M_ID(...) __VA_ARGS__
#define M_LEFT(L, R) L
#define M_RIGHT(L, R) R
#define M_FOR_EACH(ACTN, ...) M_CONC(M_FOR_EACH_, M_NARGS(__VA_ARGS__)) (ACTN, __VA_ARGS__)
#define M_FOR_EACH_0(ACTN, E) E
#define M_FOR_EACH_1(ACTN, E) ACTN(E)
#define M_FOR_EACH_2(ACTN, E, ...) ACTN(E) M_FOR_EACH_1(ACTN, __VA_ARGS__)
#define M_FOR_EACH_3(ACTN, E, ...) ACTN(E) M_FOR_EACH_2(ACTN, __VA_ARGS__)
#define M_FOR_EACH_4(ACTN, E, ...) ACTN(E) M_FOR_EACH_3(ACTN, __VA_ARGS__)
#define M_FOR_EACH_5(ACTN, E, ...) ACTN(E) M_FOR_EACH_4(ACTN, __VA_ARGS__)
#define FRUITS (apple, banana, cherry)
#define ANIMALS (dog, monkey)
#define ZOO_BLOCK(NAME, FRTS, ANMLS) struct NAME##Block { \
M_FOR_EACH(DEFINE_FRUITS, FRTS) \ // Wrong, see my question below
M_FOR_EACH(DEFINE_ANIMAL, ANMLS) \ // Wrong
}
#define DEFINE_FRUITS(F) Fruit F;
#define DEFINE_ANIMALS(F) Animal F;
ZOO_BLOCK(MyZoo, FRUITS, ANIMALS);
通过 M_FOR_EACH(DEFINE_FRUITS,FRTS)
,我愿做 M_FOR_EACH(DEFINE_FRUITS,__VA_ARGS __)
其实和 __ __ VA_ARGS
都是从水果(如苹果,香蕉,樱桃)。我怎样才能改变我的宏来做到这一点?
By M_FOR_EACH(DEFINE_FRUITS, FRTS)
, I would like to do M_FOR_EACH(DEFINE_FRUITS, __VA_ARGS__)
actually and __VA_ARGS__
are all from FRUITS (i.e. apple, banana, cherry). How can I change my macros to do this?
推荐答案
我不知道这是否是你在找什么,但parenthesised水果和动物群都没有解决。您可以使用 M_ID
宏,例如扁平化起来。
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_ID
macro, 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);
这与在 DEFINE_ANIMAL / S
收益率纠正一个小错字在一起:
This, together with correcting a minor typo in DEFINE_ANIMAL/S
yields:
struct MyZooBlock {
Fruit apple;
Fruit banana;
Fruit cherry;
Animal dog;
Animal monkey;
};
这篇关于一组可变参数宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!