timmerov
timmerov

Reputation: 179

pretty print a list of variables and values in c++

i would like to dump the names of variables and their values to stderr. the following code fragment accomplishes the task for variables one at a time:

int x=4; int y=2;
#define DUMP_VALUE(x) fprintf( stderr, "%s\n" \
  ( #x "=" + std::to_string(x) ).c_str() )
DUMP_VALUE(x);
DUMP_VALUE(y);

outputs:

x=4
y=2

so far so good. but... how do we expand that idea to a list of variables? for example, this code fragment:

int x=4; int y=2; int z=19;
DUMP_VALUES(x,y,z);

would produce this desired output:

x=4, y=2, z=19

the problem is... what combination of macros and c++11 variadic templates could do the trick?

Upvotes: 1

Views: 406

Answers (1)

Mark
Mark

Reputation: 981

You could define a variadic template with something like this:

template <class T>
void dump(T t)
{
  std::cout << "val=", << t << " ";
}

template <class T, class... Args>
void dump(T t, Args... args)
{
  dump(t);
  dump(args);
}

And call it like this:

int x = 1;
int y = 2;
int z = 3;
dump(x, y, z);

Output:

val=1, val=2, val=3

You'll have to pass in the name of the variable somehow while calling dump if you want that printed out.

Here's a decent reference site with some variadic example: http://eli.thegreenplace.net/2014/variadic-templates-in-c/

Upvotes: 1

Related Questions