Reputation: 1659
Please consider the member function template. My question is embedded in comment form.
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;
}
Upvotes: 1
Views: 107
Reputation: 53516
The <<
and >>
operators on streams are designed to work with tokens separated by whitespace. So if a string looks like "1 2" then your stringstream
will only read in 1
on the first <<
.
If you want multiple values I suggest you use a loop over the stream. Something like this might do...
//stringstream has a const string& constructor
std::stringstream ss(iter->second);
while (ss >> manipulator >> value) { /* do checks here /* }
With that I would suggest you look at Boost and in particular lexical_cast which might do what you want out of the box.
Upvotes: 2