C++11 中没有"sto{short, unsigned short}"功能?

No "sto{short, unsigned short}" functions in C++11?

本文关键字:short unsigned 功能 sto C++11      更新时间:2023-10-16

c++ 11引入了方便函数stoistolstollstoulstoullstofstodstold,分别将字符串转换为整型、长型、长型、无符号长型、无符号长型、浮点型、双精度型和长双精度型。

为什么不喜欢short和unsigned short?

除了这个遗漏让我出于原则感到恼火之外,我发现自己不得不尴尬地处理这样的情况:

#include <string>
struct S
{
    S(short);
};
int main()
{
    S s{std::stoi("4")};
}
错误:

test.cpp: In function 'int main()':
test.cpp:10:23: error: narrowing conversion from 'int' to 'short int' inside { } [-fpermissive]

我想写S s{std::stos("4")};,如果只有stos

我不得不写S s{static_cast<short>(std::stoi("4"))};…哦,等一下,这也不会做到这一点,它将默默地截断比短裤更长的整数,而不是假设的stos函数,如果整数不适合短裤,则会抛出异常。所以基本上我回到了我在c++ 11之前的stringstreams, boost::lexical_cast等替代品。

编辑:由于人们似乎很难找到我的实际问题,它是为什么没有stosstous函数与其他函数一起?

猜测:c++从C(可能是C99变体)中获取s-to-xxx函数只是为了兼容;如果c++是独立开发的,就不会有这样的函数了。