Search code examples
c++variablesprintfiostream

generic way to print out variable name in c++


given a class

struct {
  int a1;
  bool a2;
  ...
  char* a500;
  ...
  char a10000;      
}

I want to print or stream out

"a1 value is SOME_VALUE"  
"a2 value is SOME_VALUE"
"a500 value is SOME_VALUE"
...
"a10000 value is SOME_VALUE"

the type of the member variables are not the same (mainly, int, bool, char*, etc, i.e., no need to overload << operator), and the member variable name could be named with anything, i.e., no rule to follow. Instead of typing explicitely one by one (very big tedious, and error-prone work), is there any generic way?

Thanks for any comments!


Solution

  • The feature you're looking for is typically called reflection. It is not part of C++, since in compiled languages the information you're after (human-readable variable names) is generally not kept by the compiler. It is not needed to run the code, so there's no point in including it.

    Debuggers can often inspect either out-of-band symbol information, or symbol data kept in binaries for this very purpose, to show such names but re-doing that for this purpose is probably more work than it's worth.

    I would suggest looking for some of the many "tricks" (=solutions) to implement this yourself.