Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

c++11

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?

like image 247
HighCommander4 Avatar asked Oct 25 '11 20:10

HighCommander4


1 Answers

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.

like image 75
anatolyg Avatar answered Oct 24 '22 10:10

anatolyg