lundi 9 mars 2015

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?


Aucun commentaire:

Enregistrer un commentaire