是否可以为std :: string和std :: wstring编写一个函数?

Fab*_*ian 10 c++ string templates stl stdstring

我刚刚为std :: string编写了一个简单的实用函数.然后我注意到如果std::string是a std::wstring或a ,函数看起来完全一样std::u32string.这里可以使用模板功能吗?我不是很熟悉的模板,std::stringstd::wstring在模板本身,这可能是一个问题.

template<class StdStringClass>
inline void removeOuterWhitespace(StdStringClass & strInOut)
{
  const unsigned int uiBegin = strInOut.find_first_not_of(" \t\n");

  if (uiBegin == StdStringClass::npos)
  {
    // the whole string is whitespace
    strInOut.clear();
    return;
  }

  const unsigned int uiEnd   = strInOut.find_last_not_of(" \t\n");
  strInOut = strInOut.substr(uiBegin, uiEnd - uiBegin + 1);
}
Run Code Online (Sandbox Code Playgroud)

这是一个正确的方法吗?这个想法是否存在陷阱?我不是在谈论这个函数,而是使用模板化类StdStringClass并调用常见std::string函数(如find,replace,erase等)的一般概念.

Dav*_*aim 6

这是一个好主意,但我会建立模板std::basic_string而不是一般StdStringclass

template<class T>
inline void removeOuterWhitespace(std::basic_string<T>& strInOut)
{
  constexpr auto delim[] = {T(' '),T('\t'),T('\n'),T(0)};
  const auto uiBegin = strInOut.find_first_not_of(delim);

  if (uiBegin == std::basic_string<T>::npos)
  {
    // the whole string is whitespace
    strInOut.clear();
    return;
  }

  const auto  uiEnd   = strInOut.find_last_not_of(delim);
  strInOut = strInOut.substr(uiBegin, uiEnd - uiBegin + 1);
}
Run Code Online (Sandbox Code Playgroud)

我也会抛弃MSDN风格的"inout"表示法,以获得更简单的名称str.程序员会猜测自己str 结果,因为它作为非const引用和函数返回传递void.

另外,我换unsigned intauto.size_t返回索引时返回所有标准C++容器/字符串.size_t可能不是unsigned int.auto将自己与正确的返回值匹配.

  • 我建议不要明确地使用`basic_string`,这是一个很好的理由:如果我以后切换到提供我在这里使用的接口的替代字符串类怎么办?我使用`typename StringType`并使用`StringType :: value_type`来获取其底层字符类型.话虽这么说,使用某种形式的`isspace`谓词而不是硬编码的空格列表可能会更好.特别是如果使用`wstring`之类的东西(暗示多于ASCII的空格字符). (3认同)