否“sto {short,unsigned short}”函数在C ++ 11? [英] No "sto{short, unsigned short}" functions in C++11?

查看:259
本文介绍了否“sto {short,unsigned short}”函数在C ++ 11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11引入了方便功能 stoi stol stoll stoul stoull stof stod stold ,将字符串转换为整数,long,long long,unsigned long,unsigned long long ,float,double或long double。



为什么没有对短和无符号短的爱?



除了事实,遗漏让我失去原则,我发现自己必须在这样的情况下工作尴尬:

 # include< string> 

struct S
{
S(short);
};

int main()
{
S s {std :: stoi(4)};
}

错误:

  test.cpp:在函数'int main()':
test.cpp:10:23:error:narrowing从'int' } [-fpermissive]



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


$相反,我必须写 S s {static_cast< short>(std :: stoi(4))}; ... oh wait,这将不会做,它将默认截断比shorts更长的整数,而不是一个假设的 stos 函数,如果该整数不适合,将抛出一个异常短。所以基本上我回到我的前C ++ 11替代品 stringstreams boost :: lexical_cast



EDIT :由于人们似乎很难找到我的实际问题,所以为什么没有 stos stous 函数与其他函数一起


C++11 introduces convenience functions stoi, stol, stoll, stoul, stoull, stof, stod, and stold, which convert a string to an integer, long, long long, unsigned long, unsigned long long, float, double, or long double, respectively.

Why no love for short and unsigned short?

Besides the fact that the omission annoys me out of principle, I am finding myself having to work awkwardly around situations like this:

#include <string>

struct S
{
    S(short);
};

int main()
{
    S s{std::stoi("4")};
}

Error:

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

I'd like to instead write S s{std::stos("4")};, if only there were an stos...

Instead I have to write S s{static_cast<short>(std::stoi("4"))};... oh wait, that won't do it either, that will silently truncate integers longer than shorts, as opposed to a hypothetical stos function which would throw an exception if the integer does not fit into a short. So basically I'm back to my pre-C++11 alternatives of stringstreams, boost::lexical_cast, and the like.

EDIT: Since people seem to have a hard time locating my actual question, it's why are there no stos and stous functions to go along with the other ones?

解决方案

A guess: C++ took the s-to-xxx functions from C (probably the C99 variant) just for compatibility; there would be no such functions if C++ were developed independently.

这篇关于否“sto {short,unsigned short}”函数在C ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆