問題描述
如果標題不清楚,我會盡量澄清我的問題:
If the title was not clear, I will try to clarify what I am asking:
假設我有一個名為 counter 的變量,我知道我可以通過執行以下操作來查看其當前值:
Imagine I have a variable called counter, I know I can see its current value by doing something like:
std::cout << counter << std::endl;
但是,假設我有很多變量,并且直到運行時我不知道要查看哪些變量.
However, assume I have lots of variables and I don't know which I'm going to want to look at until runtime.
有誰知道我可以通過使用變量名稱獲取變量值的方法,例如:
Does anyone know a way I can fetch the value of a variable by using its name, for example:
std::cout << valueOf("counter") << std::endl;
我覺得能夠做到這一點可能會使調試大型復雜項目變得更容易.
I feel being able to do this might make debugging large complex projects easier.
提前感謝您的時間.
更新:所提供的所有答案都是有效且有用的,但重點是 C++ 中不存在反射(閱讀推薦的鏈接后很清楚原因).
Update: All the answers provided are valid and useful, however the main point is that reflection does not exist in C++ (and after reading the link recommended it is clear why).
推薦答案
如前所述,您正在尋找 C++ 中的反射.它沒有那個,這個答案解釋了原因.
As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
這篇關于在 C++ 中使用表示變量名稱的字符串訪問變量值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!