1

How can I define a macro that allows me to "dump" multiple variables to my terminal? e.g.

DUMP(foo, bar, baz);

Would print:

my_file.cpp:100: foo="value of foo", bar="barval", baz="baz's val"

I've got it working for a single arg:

#define DUMP(val) std::cerr << __FILE__ << ":" << __LINE__ << ": " << #val << "=" << (val) << std::endl

And I know I can make a variadic macro by defining it like DUMP(args...) but then I don't know how to expand that out properly into an ostream.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 1
    Since C++20 you don't need macros for this anymore. It introduces [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location). – François Andrieux Nov 24 '21 at 20:27
  • Nevermind, you still need macros to stringify your arguments. – François Andrieux Nov 24 '21 at 20:32
  • @FrançoisAndrieux Ya. Good tip about `std::source_location` tho, I'm sure that'll come in handy later. Thanks – mpen Nov 24 '21 at 20:34
  • Have you already read this: https://stackoverflow.com/questions/679979/how-to-make-a-variadic-macro-variable-number-of-arguments ? – Bob__ Nov 24 '21 at 20:35
  • @Bob__ I've seen similar answers but I don't know how to get the arg names out of `__VA_ARGS__` – mpen Nov 24 '21 at 20:38
  • 3
    Perhaps helpful: [how to print many variables with there name and their corresponding value in c++?](https://stackoverflow.com/questions/64213475/how-to-print-many-variables-with-there-name-and-their-corresponding-value-in-c/64215959#64215959) – Ted Lyngmo Nov 24 '21 at 20:43
  • 1
    @mpen I added a `source_location` version to the old answer there. It still requires a macro to expand the variable names though. I couldn't think of a way to get rid of that. – Ted Lyngmo Nov 24 '21 at 20:59
  • @TedLyngmo Cool! That's even better. Thank you – mpen Nov 24 '21 at 21:19
  • 1
    @mpen Cheers! Yeah, I noticed that one now gets the full signatures of the functions **and** one even gets template parameters. `source_location` seems really nice! – Ted Lyngmo Nov 24 '21 at 21:21

0 Answers0