In the above example, the code PRINT_ARGS("Hello, %s!\n", "world") will be expanded with printf("Hello, %s!\n", "world")。
However, if no arguments are passed into a macro that uses __VA_ARGS__, it will result in a trailing comma issue (a redundant comma ‘,’ at the end).
To avoid this error, use ##__VA_ARGS, which will remove the previosu comma when no arguments, and works the same as __VA_ARGS__ normally in other cases.
In the above example, LOG("Hello, world!\n") will be expanded to printf("Hello, world\n", ). Note that there’s an extra comma ,, so a compile error will occur.
To fix it, just replace __VA_ARGS__ with ##__VA_ARGS__.
#include<iostream> /* * Multiple args with different types. */ template<typename...U> voidprint_line(U...u){ // get the number of arguments std::cout << "There are " << sizeof...(u) << " args, namely \n"; // print them (comma expression) ((std::cout << u << ", "), ...) << std::endl; // remove the comma in the end [[maybe_unused]] int i = 0, last_index = sizeof...(u) - 1; ((i++ < last_index ? (std::cout << u << ", ") : (std::cout << u << std::endl) ), ...); }
intmain(){ // Print Line print_line(1, 2, "str", 'a'); /* Output: There are 4 args, namely, 1, 2, str, a, 1, 2, str, a */ }