c++cmacrosforeach

Foreach macro on macros arguments


I wonder if it is possible to write a macro foreach on macros arguments. Here is what want to do:

#define PRINT(a) printf(#a": %d", a)
#define PRINT_ALL(...) ? ? ? THE PROBLEM ? ? ? 

And possible usage:

int a = 1, b = 3, d = 0;
PRINT_ALL(a,b,d);

Here is what I achieved so far

#define FIRST_ARG(arg,...) arg
#define AFTER_FIRST_ARG(arg,...) , ##__VA_ARGS__     
#define PRINT(a) printf(#a": %d", a)
#define PRINT_ALL PRINT(FIRST_ARG(__VA_ARGS__)); PRINT_ALL(AFTER_FIRST_ARG(__VA_ARGS__))

This is a recursive macro, which is illegal. And another problem with that is stop condition of recursion.


Solution

  • Since you are accepting that the preprocessor has VA_ARGS (in C99, but not in the current C++ standard) you can go with P99. It has exactly what you are asking for: P99_FOR. It works without the crude ()()() syntax from BOOST. The interface is just

    P99_FOR(NAME, N, OP, FUNC,...) 
    

    and you can use it with something like

    #define P00_SEP(NAME, I, REC, RES) REC; RES
    #define P00_VASSIGN(NAME, X, I) X = (NAME)[I]
    #define MYASSIGN(NAME, ...) P99_FOR(NAME, P99_NARG(__VA_ARGS__), P00_SEP, P00_VASSIGN, __VA_ARGS__)
    
    MYASSIGN(A, toto, tutu);