在c ++中打印出变量名的通用方法 [英] generic way to print out variable name in 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 *等,即,不需要重载<< operator),并且成员变量名称可以用任何名称命名,即,不遵循规则。
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.
我建议寻找一些许多tricks(=解决方案)来自己实现。
I would suggest looking for some of the many "tricks" (=solutions) to implement this yourself.
这篇关于在c ++中打印出变量名的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!