I would like to define a macro with a variable number of parameters which prints the name and value of each given parameter.
For instance :
MACRO(x) would print x = 123
MACRO(x,y) would print x,y = 123,666
A better macro would be more readable
BETTER_MACRO(x,y) would print x = 123, y = 666
For one variable, I can manage with :
#define MACRO(...) cout << #__VA_ARGS__ << " = " << __VA_ARGS__ << endl;
For more, it does not work.
By acting this way, some auxiliary questions come to my mind.
1) How to get the number of variables given to the macro? 2) How to access each argument?
Guess naïvely, we can answer these two questions.
We then hope to define the macro in the following way.
#define BETTER_MACRO(...) {for (int i=0;i<=nb_variables;i++) {cout << #var[i] << var[i];}}
#define MACRO(...) function(#__VA_ARGS__, __VA_ARGS__)
// base case for template recursion when one argument remains
template <typename Arg1>
void function(const char* name, Arg1&& arg1)
{
std::cout << name << " = " << arg1 << std::endl;
}
// recursive variadic template for multiple arguments
template <typename Arg1, typename... Args>
void function(const char* names, Arg1&& arg1, Args&&... args)
{
const char* comma = strchr(names + 1, ',');
std::cout.write(names, comma - names) << " = " << arg1;
function(comma, args...);
}
The above has the somewhat whimsical property that whatever spacing (or not) that you include in the invocation of MACRO will be mirrored in the output.
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