成员函数模板将std :: string转换为任何数值类型或std :: string [英] Member Function Template to Covert a std::string to Any Numeric Type or to a std::string

查看:289
本文介绍了成员函数模板将std :: string转换为任何数值类型或std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑成员函数模板。我的问题嵌入在注释形式中。

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;
}


推荐答案

< >> 上的运算符设计为使用以空格分隔的标记。因此,如果一个字符串看起来像1 2,那么你的 stringstream 只会读取 1 $ c><< 。

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 /* }

有了我建议你看看Boost,特别是 lexical_cast ,它可以做你想要的东西。

With that I would suggest you look at Boost and in particular lexical_cast which might do what you want out of the box.

这篇关于成员函数模板将std :: string转换为任何数值类型或std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆