为什么 C++17 标准不允许将字符串转换为布尔值?

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

根据 cppref

std::from_chars
可以将字符串转换为整数。在 C++ 中,
bool
是整型。所以我认为下面的代码是直观且富有表现力的:

auto const sv = "true"sv;
auto b = bool{};
std::from_chars(sv.data(), sv.data() + sv.size(), b); // compiler error
assert(b);

然而,libc++ 显式删除了重载函数:

from_chars_result from_chars(const char*, const char*, bool, int = 10) = delete;

我只是想知道:

为什么 C++17 标准不允许将字符串转换为 bool?

c++ c++17 language-lawyer std language-design
1个回答
0
投票

bool
不是 整数类型

来自 [charconv.syn]:

当使用类型占位符 integer-type 指定函数时,该实现为所有 cv 未限定的有符号和无符号整数类型提供重载,并用

char
代替 integer-type

来自 [基本.根本]:

有五种标准有符号整数类型:“

signed char
”、“
short int
”、“
int
”、“
long int
”和“
long long int
”。在此列表中,每种类型至少提供与其前面的列表一样多的存储空间。还可能存在实现定义的扩展有符号整数类型。标准和扩展有符号整数类型统称为有符号整数类型

对于每个标准有符号整数类型,都存在一个对应的(但不同)标准无符号整数类型:“

unsigned char
”、“
unsigned short int
”、“
unsigned int
”、“
unsigned long int
”和“
unsigned long long int
”。同样,对于每个扩展有符号整数类型,都存在相应的扩展无符号整数类型。标准和扩展无符号整数类型统称为无符号整数类型

所以

std::from_chars
被定义为
signed char
,
short int
,
int
,
long int
,
long long int
,
unsigned char
,
unsigned short int
,
unsigned int
,
unsigned long int
,
unsigned long long int 
 char
(以及任何实现定义的扩展整数类型)。由于
bool
不属于这些类型,因此未为其定义
std::from_chars


需要注意的是,即使

bool
属于整数类型,它也不会执行您想要的操作。
std::from_chars
仅接受数字(可能带有前导
-
符号)。
"true"
无法解析成功。

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