Get the last argument of varying argument macro function


Is it possible to get the last argument of a macro function with varying argument count

Something like:

#define foo(...,var)(var __VA_ARGS__)

but this gets an error.




I found a solution here in SO:

https://stackoverflow.com/a/24010059/15578244


but it does not extract the last one from __VA_ARGS__

like when you do this..

(var,....)(var __VA_ARGS__)


I think you want to move the last element to the front, right?
e.g.,
foo(a, b, c, d)
should expand to
d, a, b, c

To do it, add this to the stack overflow answer
1
2
3
4
5
6
7
#define DROP_LAST_pattern_1(a)
#define DROP_LAST_pattern_2(a, b) a
#define DROP_LAST_pattern_3(a, b, c) a, b
#define DROP_LAST_pattern_4(a, b, c, d) a, b, c
// extend as needed
#define DROP_LAST0(n, ...) M_CONC(DROP_LAST_pattern_, n)(__VA_ARGS__)
#define DROP_LAST(...) DROP_LAST0(M_NARGS(__VA_ARGS__), __VA_ARGS__) 
Then define foo as:
 
#define foo(...) M_GET_LAST(__VA_ARGS__), DROP_LAST(__VA_ARGS__) 

Last edited on
Topic archived. No new replies allowed.