Dmi*_*nov 5 c++ stdstring stoi
为了提高性能,我尝试std::string用自定义专业化来替代,std::basic_string其中我用自定义分配器替换标准分配器。有一件事让我感到惊讶:std::stoi函数类需要不断引用std::string(或std::wstring) 作为输入,因此这些函数不能与其他专业化一起使用。但从逻辑上讲,这些函数不应该关心内存是如何分配的;所以他们的签名看起来过于限制。
虽然我可以使用std::from_chars从任何类似字符串的数据中读取整数,但我仍然想知道是否有这样设计的原因std::stoi,以及是否还有其他设计用于与std::basic_string模板一起使用的 STL 函数。
S.M*_*.M. -1
因为它只是 C 的代理函数std::strtol(),所以在调用[1] [2]后将其错误转换为 C++ 异常
std::strtol(str.c_str(), &ptr, base)
Run Code Online (Sandbox Code Playgroud)
只接受以char*null 结尾的 char 数组,因此不接受char_type的其他特化。std::basic_string
您可以使用自定义分配器重载strtolfor std::basic_string,但必须在没有std::名称空间限定的情况下调用它:
using std::stoi;
int stoi(const mystring& str, std::size_t* pos = nullptr, int base = 10) {
char *ptr;
const long ret = std::strtol(str.c_str(), &ptr, base);
// Required checks and throwing exceptions here
if (pos)
pos = ptr - str.c_str();
return static_cast<int>(ret);
}
Run Code Online (Sandbox Code Playgroud)
至于std::string_view,不需要引用以 null 结尾的字符串,因此它不具有std::string_view::c_str()并且data()不适合std::strtol()。