繁体   English   中英

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

[英]Is it possible to write one function for std::string and std::wstring?

我只是为std :: string写了一个简单的实用函数。 然后我注意到,如果std::stringstd::wstringstd::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);
}

这是正确的方法吗? 这个想法有陷阱吗? 我不是在谈论这个功能,而是使用模板类StdStringClass并调用通常的std::string函数(如查找,替换,擦除等)的一般概念。

这是一个好主意,但我会在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 结果,因为它作为非常量引用传递且函数返回void

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

假设您的模板按预期工作(未选中...抱歉),另一种选择是将函数包装在类中,并控制您希望使用构造函数将函数应用于哪些字符串类类型。

编辑 :添加了说明性框架

EDIT2编译(至少与vs2015一起编译):-)

class StringType1;
class StringTypeN;

class str {

    //template function
    template<class StdStringClass>
    inline void removeOuterWhitespace(StdStringClass & strInOut)
    {
        //.
        //.
        //.
    }

public:
    //constructors
    str(StringType1 &s1) { removeOuterWhitespace(s1); }
    //.
    //.
    //.
    str(StringTypeN &sN) { removeOuterWhitespace(sN); }


};

int main() {

    return 0;
}

EDIT3概念验证

#include <iostream>
class incr {
    //template function
    template<class incrementor>
    inline void removeOuterWhitespace(incrementor & n)
    {
        n++;
    }
public:
    //constructors
    incr(int &n1) { removeOuterWhitespace(n1); }
    incr(double &n1) { removeOuterWhitespace(n1); }
    incr(float &n1) { removeOuterWhitespace(n1); }
};

int main() {
    int n1 = 1;
    double n2 = 2;
    float n3 = 3;
    std::cout << n1 << "\t" << n2 << "\t" << n3 << std::endl;
    auto test1 = incr(n1);
    auto test2 = incr(n2);
    auto test3 = incr(n3);
    //all variables modified
    std::cout << "all variables modified by constructing incr" << std::endl;
    std::cout << n1 << "\t" << n2 << "\t" << n3 << std::endl;
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM