어떤 용어를 사용해야할지 모르므로 코드로 시작해야합니다. 나는 다음과 같은 코드가 있다고 가정하자 : 내가 참을 수 없어하는 경우 (STRCMP (attr-> 이름(), "X")!) 컨버터 >> x의 반복이다문자열 값을 기준으로 멤버를 지정하십시오.
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;
};
; 이 오류가 발생하기 쉽고 단조롭다 고 생각하지만 문자열 값을 멤버 할당에 매핑하는 다른 방법을 생각할 수 없습니다. 이 같은 코드를 피하기 위해 취할 수있는 다른 접근 방법은 무엇입니까? 내가 생각할 수있는 유일한 다른 가능한 대안은 해시 맵을 사용했지만, 그 콜백
이 내가 함께 할 수있는 최선입니다 문제로 실행하지만, 내가 원하는만큼 그것은 유연 아니다 :
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())
{
map<std::string, float*>::iterator member = assignmentMap.find(attr->name());
//check for a pre-existing entry
if(member == assignmentMap.end()) continue;
std::stringstream converter;
converter << attr->value();
converter >> *(member->second);
}
}
private:
float x;
float y;
float z;
std::map<std::string, float*> assignmentMap;
};
코드 마크 업은 코드를 선택하고 다음 번에 편집기에서 '101'버튼을 사용하십시오. –
오, 그게 어떻게 완료됩니다, 감사합니다, noscript는 googelapi를 차단하고 있었고 난 항상 혼란스러워했습니다! – Apeiron
두 번째 해결 방법에 버그가 있습니다. 'std :: map :: operator []'는 지정된 키를 가진 엔트리가 존재하지 않는다면 그 엔트리를 생성 할 것이고, 그래서 여러분의 코드가 맵에없는 속성 이름을 가로 질러 오면, 새로 만든 포인터 (NULL로 초기화됩니다, 나는 꽤 확신합니다). iter = assignmentMap.find (attr-> name()); if (iter! = assignmentMap.end()) 변환기 >> * (iter-> second)'. –