【发布时间】:2016-06-16 12:19:26
【问题描述】:
我刚刚为 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需要一些技巧,因为字符类型不同。例如,上面的函数不适用于std::wstring,因为std::wstring::find_first_not_of不采用const char*,而是采用const wchar_t*。 -
除了
unsigned int之外,我建议使用typename StdStringClass::size_type或者如果启用了c++11,则使用auto。 -
@Benjamin 也许搜索到的字符串
" \t\n"应该换成StdStringClass(" \t\n"),它解决了吗? -
@Radek:不,因为那会尝试调用
wstring不存在的构造函数。
标签: c++ string templates stl stdstring