给定一个类
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.
这篇关于在 C++ 中打印出变量名的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么两个函数的地址相同?Why do two functions have the same address?(为什么两个函数的地址相同?)
为什么 std::function 的初始化程序必须是可复制构Why the initializer of std::function has to be CopyConstructible?(为什么 std::function 的初始化程序必须是可复制构造的?)
混合模板与多态性mixing templates with polymorphism(混合模板与多态性)
我什么时候应该使用关键字“typename"?使用模When should I use the keyword quot;typenamequot; when using templates(我什么时候应该使用关键字“typename?使用模板时)
依赖名称解析命名空间 std/标准库Dependent name resolution amp; namespace std / Standard Library(依赖名称解析命名空间 std/标准库)
gcc 可以编译可变参数模板,而 clang 不能gcc can compile a variadic template while clang cannot(gcc 可以编译可变参数模板,而 clang 不能)