在 C++ 中打印出变量名的通用方法

2021-12-13 00:00:00 variables printf iostream c++

给定一个类

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

我想打印或流式输出

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

成员变量的类型不一样(主要是int、bool、char*等,即不需要重载<<运算符),成员变量名可以任意命名,即,没有规律可循.有没有一种通用的方法,而不是一个一个地明确输入(非常繁琐且容易出错的工作)?

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?

感谢您的评论!

推荐答案

您正在寻找的功能通常称为 反射.它不是 C++ 的一部分,因为在编译语言中,您所追求的信息(人类可读的变量名)通常不会被编译器保留.不需要运行代码,所以包含它没有意义.

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.

相关文章