Get value from String containing Variable Name?

As written in the title, I want to be able to extract a variable value from a string containing the variable's name. I know one can use associative containers such as maps but is there another more direct way?

1
2
3
4
5
6
eg:

int variable = 5;

string str = "variable";
// how do I get the value of 5 out of the string containing the variable name? 



If I am correct, this is called 'Reflection', correct me if I'm wrong.

I know C++ has no inbuilt 'Reflection' class or anything like that so I was wondering if there is a workaround for this kind of thing or is there a library out there which can do this? (that's if I have the name right).

I have found a library called Boost Reflection which sounds like it could do this but I just wanted to make sure that reflection is actually what I am talking about and whether C++ can do what I'm trying to do? I'm not sure how.
is there another more direct way?


No. Because there is no entity named variable in resulting code. Variable names is just aliases to make it easy to work with them. Even if reflection would be part of language (there are proposals), (1) it would work on types and its members and not on variable names and (2) it would not work on builtin types anyway.

Every language allowing lookup of the variable by its name is managing map of names/memory locations of variables internally. You just not see it.

Using custom classes you can achieve something like:
1
2
3
4
managed_var<int>("variable");
lookup<int> str = "variable";
*str = 5;
std::cout << *str;
Yep,, Associative container, as I thought.
Was hoping there was another way though the map is fine.

Thanks
http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c
That's another way you could do it, and the way I do it.
You've misinterpreted the question. Back the front :)
Registered users can post here. Sign in or register to post.