Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable value using string representing variable's name in C++ [duplicate]

Tags:

c++

variables

If the title was not clear, I will try to clarify what I am asking:

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.

Thanks in advance for your time.


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).

like image 452
Paul Ridgway Avatar asked May 26 '10 08:05

Paul Ridgway


1 Answers

As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.

like image 54
Björn Pollex Avatar answered Nov 12 '22 10:11

Björn Pollex