generic way to print out variable name in c++(在 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.
这篇关于在 C++ 中打印出变量名的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中打印出变量名的通用方法
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01