访问变量值使用C ++中表示变量名称的字符串
如果标题不清楚,我将尝试澄清我的问题:
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.