I’m a fan of debug printing when trying to investigate problems in my code:
cout << "foo:" << foo << "bar:" << bar << "baz:" << baz;
Since I write code like this very often, it would be awesome if I could make it generic and easier to type. Maybe something like this:
DEBUG_MACRO(foo, bar, baz);
Even though foo, bar, and baz resolve to variable names, not strings, is it possible to use their variable names to create the strings "foo:", "bar:", and "baz:"? Can you write a function or macro that takes an unspecified number of parameters?
If you have C++11 you can do something typesafe and fairly neat with variadic templates, e.g.:
The NVP macro here is entirely optional and only needed if you want to print the name you referred to it by in the code as well.
If you really want to skip the NVP bit you can use the Boost pre-processor library (or roll your own) e.g.:
for the price of some slightly odd syntax. My example is based on this answer. I tried to use variadic macros to solve this directly as a “pure” C++11 solution, but it turns out recursing through a list is trickier than you’d hope with it.