Is it possible to write a preprocessor macro such that would transform a variable number of arguments into successive function calls, such as
MAP(f, 1, 2, 3, ..., n)
into
f(1); f(2); f(3); ... f(n);
So far, I've got following, which seems to work:
#define MAP(f, t, ...) \
{\
t __varlist[] = {__VA_ARGS__};\
for(int i = 0; i < sizeof(__varlist) / sizeof(t); i++)\
f(__varlist[i]);\
}
Note that this macro takes a type parameter so that it can be a bit more useful.
Is there a way to do it without declaring a temporary? Or does it not matter, because the compiler is so smart that it figures out everything? I'm kind of new to C.
use boost.
note:limit size 256. BOOST_PP_LIMIT_SEQ
#include <stdio.h>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>
#define PROC(r, f, elem) f(elem);
//#define MAP(f, ...) BOOST_PP_SEQ_FOR_EACH(PROC, f, BOOST_PP_TUPLE_TO_SEQ(BOOST_PP_TUPLE_SIZE((__VA_ARGS__)),(__VA_ARGS__)))
#define MAP(f, ...) BOOST_PP_SEQ_FOR_EACH(PROC, f, BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))
void f(int data){
printf("%d\n", data);
}
int main(){
MAP(f, 1, 2, 3);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With