Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no std::from_string()?

Why is there no

template <typename T>
T std::from_string(const std::string& s);

in the C++ standard? (Seeing how there's an std::to_string() function, I mean.)

PS - If you have an idea for the reason this was not adopted/considered, just answer/comment and say what it is, rather than downvoting. I'm not actually making a proposal that this be included in the standard.

like image 208
einpoklum Avatar asked Aug 26 '16 15:08

einpoklum


1 Answers

As Nicol Bolas pointed out, to_string is never a template, but just a group of overloaded functions. Making such functions templates are not good, as doing them generically is probably not efficient, and can only behave like stringstreams. So from_string, similarly, should not be function templates, but rather simple functions. Since their argument is the same type (std::string), their names should not be the same. So stoi, stof, and the like are really what you wanted.

to_string and sto* also behave similarly regarding the locale: they all respect the current C locale. The C++ IOStreams, on the contrary, are not affected by the C locale. They can be overridden only if they are created after the C++ global locale is set by std::locale::global, or are manually imbue’d with a different locale.

like image 73
Yongwei Wu Avatar answered Sep 19 '22 12:09

Yongwei Wu