我想將一組可變參數傳遞給一個宏。我有以下宏這是不正確的:一組可變參數宏
#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__
都是從水果(例如蘋果,香蕉,櫻桃)。我怎樣才能改變我的宏來做到這一點?
如果你真的需要這一點,使用Boost的預處理器庫。 – chris 2014-10-27 06:47:25
如果我們不使用boost庫會怎麼樣? – yuefengz 2014-10-27 06:58:28
@Fake他們你在很大程度上重新發明輪子。 – Angew 2014-10-27 07:38:21