assign member based on string value
- by Aperion
I need start off with code because I am not sure what terminology to use. Lets say I have the following code:
class Node
{
public:
void Parse(rapidxml::xml_node<> *node)
{
for (rapidxml::xml_attribute<> *attr = node->first_attribute();
attr;
attr = attr->next_attribute())
{
std::stringstream converter;
converter << attr->value();
if( !strcmp(attr->name(), "x") ) converter >> x;
else if( !strcmp(attr->name(),"y") ) converter >> y;
else if( !strcmp(attr->name(), "z") ) converter >> z;
}
}
private:
float x;
float y;
float z;
};
What I can't stand is the repetition of if( !strcmp(attr-name(), "x") ) converter x; I feel that this is error prone and monotonous, but I cannot think of another way to map a string value to a member assignment. What are some other approaches one can take to avoid code such as this? The only other possible alternative I could think of was to use a hashmap, but that runs into problems with callbacks
This is the best I could up with but it's not as flexible as I'd like:
class Node
{
Node() : x(0.0f), y(0.0f), z(0.0f)
{
assignmentMap["x"] = &x;
assignmentMap["y"] = &y;
assignmentMap["z"] = &z;
}
public:
void Parse(rapidxml::xml_node<> *node)
{
for (rapidxml::xml_attribute<> *attr = node->first_attribute();
attr;
attr = attr->next_attribute())
{
if( !attr->name() ) continue;
std::stringstream converter;
converter << attr->value();
converter >> *assignmentMap[attr->name()];
}
}
private:
float x;
float y;
float z;
std::map<std::string, float*> assignmentMap;
};