我刚刚为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
函数,如find、 replace、erase等时,是否存在问题?我指的不是这个函数,而是使用模板类的一般概念。
std::wstring
将无法工作,因为std::wstring::find_first_not_of
接受的是const wchar_t*
而不是const char*
。 - Benjamin Lindleyunsigned int
,我建议使用typename StdStringClass::size_type
或者如果启用了 C++11,则使用auto
。 - Radek" \t\n"
包装到StdStringClass(" \t\n")
中,这样可以解决问题吗? - Radekwstring
不存在的构造函数。 - Benjamin Lindleytrim
。 - Orwellophile