問題描述
給定一個類
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*等,即不需要重載<<運算符),成員變量名可以任意命名,即,沒有規(guī)律可循.有沒有一種通用的方法,而不是一個一個地明確輸入(非常繁瑣且容易出錯的工作)?
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.
調試器通常可以檢查帶外符號信息,或為此目的保存在二進制文件中的符號數據,以顯示此類名稱,但為此目的重新執(zhí)行此操作可能比它的價值更多.
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模板網!