C++ 11引入方便的功能stoi
,stol
,stoll
,stoul
,stoull
,stof
,stod
,和stold
,其中一个字符串转换为整数,很久长,无符号长,无符号长长整型,浮点,双,或双长分别.
为什么不爱短暂和无条件的短片?
除了遗漏让我原谅我的事实外,我发现自己不得不在这样的情况下笨拙地工作:
#include <string>
struct S
{
S(short);
};
int main()
{
S s{std::stoi("4")};
}
Run Code Online (Sandbox Code Playgroud)
错误:
test.cpp: In function 'int main()':
test.cpp:10:23: error: narrowing conversion from 'int' to 'short int' inside { } [-fpermissive]
Run Code Online (Sandbox Code Playgroud)
我想反而写S s{std::stos("4")};
,如果只有stos
...
相反,我必须写S s{static_cast<short>(std::stoi("4"))};
...哦等等,也不会这样做,它会默默地截断整数而不是短路,而不是一个假设的stos
函数,如果整数不适合短路则抛出异常.所以基本上我回到我的预C++ 11层的替代品stringstreams
,boost::lexical_cast
等等.
编辑:既然人们似乎也很难定位我的实际问题,这是为什么没有stos
和stous
功能,以及其他的人去?
猜测:C++ 从 C(可能是 C99 变体)中采用了 s-to-xxx 函数,只是为了兼容性;如果C++独立开发的话就不会有这样的功能了。