string as object name

Feb 1, 2010 at 5:37pm
Hi
I have a function that takes an object as parameter. I want the user to be able to input what object to pass to the function. I was thinking it would be easiest to make input go to a string with the object name and pass that string to the function, but doesn't seem to be working. The compiler complains about not being able to convert string to class.
How do I do this?
Feb 1, 2010 at 5:50pm
It's impossible, directly. C++ doesn't have reflection, so the compiled program has no idea what an object was called in the source.

Suppose you have the objects you want to pass in an array A. What you do is establish a relation between the string "foo" and the object A[0], between the string "bar" and the object A[1], etc.
There are aseveral ways to do this. One could be:
1
2
3
4
5
6
7
8
9
std::string names[]={"foo","bar","baz"};
T A[]={foo,bar,baz};
std::string s="bar"
for (int a=0;a<3;a++){
    if (s==names[a]){
        std::cout <<A[a]<<std::endl;
        break;
    }
}


There's also std::map, which allows you to efficiently relate keys to values:
1
2
3
4
5
std::map<std::string,T> map;
map["foo"]=foo;
map["bar"]=bar;
map["baz"]=baz;
std::cout <<map["bar"]<<std::endl;
Feb 2, 2010 at 10:30pm
Great, thanks for the help.
Feb 2, 2010 at 10:41pm
with std::map, would you do this:

1
2
3
4
map<int,T> map;
map[0]=zero;
...
cout << map[0]<<endl;


...to name the keys in integers?

P.S. I use using namespace std;So I normally wouldn't do std::cout...
Topic archived. No new replies allowed.