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

generic way to print out variable name in c++(在 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++ 中打印出变量名的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)