请考虑成员函数模板。我的问题已嵌入评论表格中。
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;
}
最佳答案
流上的<<
和>>
运算符旨在与由空格分隔的 token 一起使用。因此,如果字符串看起来像“1 2”,那么您的stringstream
将仅在第一个1
上以<<
读取。
如果需要多个值,建议您在流中使用循环。这样的事情可能会做...
//stringstream has a const string& constructor
std::stringstream ss(iter->second);
while (ss >> manipulator >> value) { /* do checks here /* }
这样做之后,我建议您查看Boost,尤其是lexical_cast,它可能会开箱即用。