簡體   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