user1235183 user1235183 - 2 months ago 17
C++ Question

C++ Macro Magic: getting for every macro parameter, the parameter count number

I've to write a lot of code like this.

foo.setArg(0, arg_0);
foo.setArg(1, arg_1);
...
foo.setArg(n, arg_n);


Where n is compile-time specific and the arg_n are of different types;

I want a variadic macro which i can call like this
MACRO_MAGIC(arg_0,arg_1,...,arg_n)


I know how to get the total number of arguments but i didn't succeed in getting it managed.

Edit: from (non-sense) statement n is runtime specific to compile-time specific

Answer Source

I found the answer myself:

#define IT_CHOOSER2(name,count) name##count
#define IT_CHOOSER1(name,count) IT_CHOOSER2(name,count)
#define IT_CHOOSER(name,count)  IT_CHOOSER1(name,count)

#define IT_SET_ARGS_PREFIX IT_SET_ARGS_
#define IT_SET_ARGS_1( foo, arg_1) kernel.setArg(0, arg_1)
#define IT_SET_ARGS_2( foo, arg_1, arg_2) kernel.setArg(0, arg_1); kernel.setArg(1, arg_2)

...

#define IT_SET_ARGS(foo,...)\
IT_GLUE(IT_CHOOSER(IT_SET_ARGS_PREFIX,IT_N_ARGS(__VA_ARGS__)), (kernel,__VA_ARGS__))

But i want to mention that Jarod42 solution is much better if c++11 is available.