|
Boost Users : |
Subject: Re: [Boost-users] Looping through variadic macro arguments
From: Edward Diener (eldiener_at_[hidden])
Date: 2016-03-21 10:39:52
On 3/21/2016 4:55 AM, Florian Lindner wrote:
> Hey,
>
snipped ...
>
> I also want to write some text between the sequence items, I have made
> it working with that code:
>
> #define PRINT(r, data, elem) \
> cout << "Argument " << r-1 << ": " << elem << endl;
>
> #define vmacro(expr, ...) \
> cout << "Expression: " << #expr << endl; \
> BOOST_PP_SEQ_FOR_EACH(PRINT, ,
> BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \
>
> So, invoking vmacro(1-2, 5, 6, "Hallo"); prints
>
> #define PRINT(r, data, elem) \
> cout << "Argument " << r-1 << ": " << elem << endl;
>
> #define vmacro(expr, ...)
> \ cout << "Expression: " << #expr << endl; \
> BOOST_PP_SEQ_FOR_EACH(PRINT, ,
> BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)); \
>
>
> Expression: 1-2
> Argument 1: 5
> Argument 2: 6
> Argument 3: Hallo
>
>
> Any comments on that? How to do it better? Maybe without a helper macro
> PRINT?
> I'm a bit surprised I have to use r-1 to get 1 for the first argument.
The PRINT macro is fine. Almost all Boost PP looping constructs use a
helper macro like that.
In real life code I would name all macros in uppercase and give them a
very distinct name to reduce clashes with other potential C++
identifiers and macros.
Look at BOOST_PP_SEQ_FOR_EACH_I to get the actual argument index instead
of using 'r'.
That 'r' in your code above is actually 2,3, and 4 is just luck. The
'next available BOOST_PP_FOR repetition' as described in the doc just
happened to be 2,3, and 4 but could theoretically have been any PP
number each time and is not related to the index of each argument.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net