gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:14:28 26 4
gpt4 key购买 nike

我刚刚为 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_tsize_t 可能不是 unsigned intauto 将自身匹配到正确的返回值。

关于c++ - 是否可以为 std::string 和 std::wstring 编写一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35767678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com