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 :)
I thought I would add this in because it solves my problem completely and I just wanted to share it.

While C++ doesn't have any direct ability to parse formulas, I found a perfect C++, cross platform, free library which will do just this. I can't believe it, it's exactly what I was looking for.

The library is called muparser and it's very very easy to use. Fantastic, it's just saved me hours of trying to build something like this myself.

http://muparser.beltoforion.de/

I hope someone else out there finds it useful.
Topic archived. No new replies allowed.