为什么 stoi 不允许 std::basic_string 作为输入?

问题描述 投票:0回答:1

为了提高性能,我尝试用

std::string
的自定义专业化来替换
std::basic_string
,其中我用自定义分配器替换标准分配器。有一件事让我感到惊讶:
std::stoi
类函数需要不断引用
std::string
(或
std::wstring
)作为输入,因此这些函数不能与其他专业化一起使用。但从逻辑上讲,这些函数不应该关心内存是如何分配的;所以他们的签名看起来过于有限。

虽然我可以使用

std::from_chars
从任何类似字符串的数据中读取整数,但我仍然想知道
std::stoi
是否有这样设计的原因,以及是否有其他 STL 函数设计用于与
std::basic_string
一起使用模板。

c++ stdstring stoi
1个回答
1
投票

因为它只是 C

std::strtol()
的代理函数,在调用 [1] [2]

后将其错误转换为 C++ 异常
std::strtol(str.c_str(), &ptr, base)

仅需要

char*
,以 null 结尾的字符数组,因此不接受
char_type
的其他
std::basic_string
特化。

您可以使用自定义分配器为

strtol
重载
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);
}

对于

std::string_view
,不需要引用以空结尾的字符串,因此它没有
std::string_view::c_str()
,并且它的
data()
不适合
std::strtol()

© www.soinside.com 2019 - 2024. All rights reserved.