[英]Is it possible to write one function for std::string and 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(" \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.