Transtyper tous les parameters passés dans MACRO à l’aide de __VA_ARGS__

J’ai une macro FOO(...) qui reçoit un nombre inconnu de parameters. Je veux lancer tous ces parameters à uint. Y a-t-il un moyen d’y parvenir?

Oui, en utilisant ces macros d’utilitaires, vous pouvez appliquer une macro à chaque argument (jusqu’à 8 pour ceux-ci mais ils pourraient être développés pour plus):

 /* This counts the number of args */ #define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N #define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1) /* This will let macros expand before concating them */ #define PRIMITIVE_CAT(x, y) x ## y #define CAT(x, y) PRIMITIVE_CAT(x, y) /* This will call a macro on each argument passed in */ #define APPLY(macro, ...) CAT(APPLY_, NARGS(__VA_ARGS__))(macro, __VA_ARGS__) #define APPLY_1(m, x1) m(x1) #define APPLY_2(m, x1, x2) m(x1), m(x2) #define APPLY_3(m, x1, x2, x3) m(x1), m(x2), m(x3) #define APPLY_4(m, x1, x2, x3, x4) m(x1), m(x2), m(x3), m(x4) #define APPLY_5(m, x1, x2, x3, x4, x5) m(x1), m(x2), m(x3), m(x4), m(x5) #define APPLY_6(m, x1, x2, x3, x4, x5, x6) m(x1), m(x2), m(x3), m(x4), m(x5), m(x6) #define APPLY_7(m, x1, x2, x3, x4, x5, x6, x7) m(x1), m(x2), m(x3), m(x4), m(x5), m(x6), m(x7) #define APPLY_8(m, x1, x2, x3, x4, x5, x6, x7, x8) m(x1), m(x2), m(x3), m(x4), m(x5), m(x6), m(x7), m(x8) 

Alors maintenant, votre macro FOO pourrait être définie comme suit:

 #define FOO_EACH(x) (uint) x #define FOO(...) APPLY(FOO_EACH, __VA_ARGS__) 

Résultant en ceci:

 FOO(x, y) // Expands to (uint) x, (uint) y