1

メンバー関数テンプレートを検討してください。私の質問はコメントフォームに埋め込まれています。

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

1 に答える 1

2

ストリームの<<and>>演算子は、空白で区切られたトークンを操作するように設計されています。したがって、文字列が「1 2」のように見える場合stringstream1最初の<<.

複数の値が必要な場合は、ストリームでループを使用することをお勧めします。このような何かができるかもしれません...

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

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

それで、Boost、特に、すぐに使いたいことができるlexical_castを確認することをお勧めします。

于 2013-03-12T00:15:31.220 に答える