c++ - Variadic macro argument count not working as expected -
so, i'm trying implement macro count number of arguments in va_args.
for sake of simplicity works 3 parameters. problem when macro used less 3 parameters, doesn't work, , triggers "expected expression" error.
#define expand( x ) x #define pp_narg(...) expand(pp_arg_n(__va_args__, pp_rseq_n())) #define pp_arg_n(_1, _2, _3, n,...) n #define pp_rseq_n() 3,2,1,0 void main() { printf("\ntest pp_narg: %i", pp_narg()); //doesn't work (in case shouldn't work, it's correct) printf("\ntest pp_narg: %i", pp_narg(0)); //doesn't work printf("\ntest pp_narg: %i", pp_narg(0,0)); //doesn't work printf("\ntest pp_narg: %i", pp_narg(0,0,0)); //works }
keeping line works compiles correctly , prints "test pp_narg: 3".
i believe problem might pp_rseq_n() expanding "3", instead of "3,2,1,0" reason, since if pp_rseq_n() defined this
#define pp_rseq_n() 10,9,8,7,6,5,4,3,2,1,0
it still doesn't work less 3 parameters.
im using msvc compiler , may cause of problem, since doesn't behave macros, seen here: msvc doesn't expand __va_args__ correctly
in implementation pp_rseq_n()
argument pp_arg_n
. argument, expanded in argument substitution phase of preprocessing, happens prior replacing argument in replacement list (so long as, in replacement list, it's not being stringified , not participating in paste).
since pp_arg_n
has fourth argument n
in replacement list, pp_rseq_n()
expand if happen pass 3 arguments in. (there second scan during rescan , replacement phase, applies after argument substitution... has no effect here pp_rseq_n()
mentioned in call).
get rid of macro , put in pp_narg
this:
#define expand( x ) x #define pp_narg(...) expand(pp_arg_n(__va_args__, 3,2,1,0)) #define pp_arg_n(_1, _2, _3, n,...) n
...and things "work" fine:
pp_narg()
expands 1
pp_narg(x)
expands 1
pp_narg(x,y)
expands 2
note, however, pp_narg()
doesn't give 0. arguably that's correct; preprocessor, not passing 0 arguments. it's passing 1 argument empty. it's same thing #define x(a) open close
/x()
yielding open close
. if reason want expand 0, there may finagling happen, answer i'm focusing on getting on 1 hump.
Comments
Post a Comment