Re: Access class members by its string label
KK <pedagani@gmail.com> writes:
On Jun 30, 1:36?am, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
KK <pedag...@gmail.com> writes:
I missed my point a bit. What if the class has 1000 variables instead
of just 3?
Then definitely use a map.
Is there anyway I could skip the process of creating a map
for each and every variable and instead use an iterator to loop
through all the members until I find a match.
What do you think java does to match the name of the slot to the slot itself?
Yes, a map.
Now if you are complaining that C++ is lower level than Java, there
you get what you asked for.
--
__Pascal Bourguignon__
That was insightful. Is there a sample code which exemplifies this
idea?
No I dont actually use 1000 variables in my code. I just meant to push
the problem to make one think out of the box.
class WithALotoSlots {
private:
typedef std::map<std::string,Object> SlotMap;
SlotMap slots;
public:
void setSlot(const std::string& slotName,Object& slotValue){
slots[slotname]=slotValue;
}
Object& getSlot(const std::string& slotName){
SlotMap::iterator it=slots.find(slotName);
if(it==slots.end()){
throw std::exception((std::string("Unknown slot named ")+slotName).c_str());
}else{
return(it->second);
}
}
}
void example(){
WithALotoSlots w;
w.setSlot("x")=Object(1.0);
w.getSlot("x").print();
}
--
__Pascal Bourguignon__