加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:43:46 所属栏目:百科 来源:网络整理
导读:我刚刚为std :: string写了一个简单的效用函数.然后我注意到,如果std :: string是std :: wstring或std :: u32string,那么这个函数看起来是完全相同的.是否可以在这里使用模板功能?我不太熟悉模板,std :: string和std :: wstring是模板本身,这可能是一个问题
我刚刚为std :: string写了一个简单的效用函数.然后我注意到,如果std :: string是std :: wstring或std :: u32string,那么这个函数看起来是完全相同的.是否可以在这里使用模板功能?我不太熟悉模板,std :: string和std :: wstring是模板本身,这可能是一个问题.
template<class StdStringClass>
inline void removeOuterWhitespace(StdStringClass & strInOut)
{
  const unsigned int uiBegin = strInOut.find_first_not_of(" tn");

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

  const unsigned int uiEnd   = strInOut.find_last_not_of(" tn");
  strInOut = strInOut.substr(uiBegin,uiEnd - uiBegin + 1);
}

这是一个正确的方法吗?这个想法有没有陷阱.我不是在说这个功能,而是使用一个模板化的StdStringClass和调用通常的std :: string函数的一般概念,比如find,replace,erase等.

解决方法

它是一个很好的想法,但是我将在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);
}

我也会在favro中使用MSDN风格的“inout”符号来更简单的名字,如str.程序员会自己猜测,str是结果,因为它被传递为非const引用,函数返回void.

另外,我将unsigned int更改为auto.返回索引时,所有标准的C容器/字符串返回size_t. size_t可能不是unsigned int.自动匹配到正确的返回值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读