2013-03-12 2 views
1

멤버 함수 템플릿을 고려하십시오. 내 질문은 의견 양식에 포함되어 있습니다. 스트림에멤버 함수 std :: string을 숫자 형식 또는 std :: string으로 변환하는 템플릿

template<typename T> 
GetValueResult GetValue(
          const std::string &key, 
          T &val, 
          std::ios_base &(*manipulator)(std::ios_base &) = std::dec 
         ) 
{ 
    // This member function template is intended to work for all built-in 
    // numeric types and std::string. However, when T = std::string, I get only 
    // the first word of the map element's value. How can I fix this? 

    // m_configMap is map<string, string> 
    ConfigMapIter iter = m_configMap.find(key); 

    if (iter == m_configMap.end()) 
     return CONFIG_MAP_KEY_NOT_FOUND; 

    std::stringstream ss; 
    ss << iter->second; 

    // Convert std::string to type T. T could be std::string. 
    // No real converting is going on this case, but as stated above 
    // I get only the first word. How can I fix this? 
    if (ss >> manipulator >> val) 
     return CONFIG_MAP_SUCCESS; 
    else 
     return CONFIG_MAP_VALUE_INVALID; 
} 

답변

2

<<>> 연산자는 공백으로 구분 된 토큰과 함께 작동하도록 설계되었습니다. 따라서 문자열이 "1 2"로 표시되면 stringstream<<1으로 읽습니다.

값이 여러 개인 경우 스트림을 통해 루프를 사용하는 것이 좋습니다. 그와 함께 할 수있는 이런 식으로 뭔가 ...

//stringstream has a const string& constructor 
std::stringstream ss(iter->second); 

while (ss >> manipulator >> value) { /* do checks here /* } 

난 당신이 부스트을보고 특정 lexical_cast 당신이 상자 밖으로 원하는 것을 할 수있는 제안했다.

+0

문자열의 * 마지막 * 부분을 읽지 않습니까? 나는'value'가 문장이 실행될 때마다 덮어 쓰여진다 고 생각한다. –

관련 문제