Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a complement to std::to_string()?

Tags:

c++

c++11

In C++11, since there is a standard std::to_string(), I overload this function for enumeration classes and other small data classes where an implementation makes sense.

My question is, what do you implement as a complement to std::to_string()?

Some kind of from_string() (which doesn't exist in std) or is there a more appropriate standard interface you implement throughout your classes?

like image 772
kfmfe04 Avatar asked May 05 '26 23:05

kfmfe04


2 Answers

the standard using uses the terse naming scheme used in old C. so where you have

std::string to_string( int value );

you have

int std::stoi(std::string);

see here

http://en.cppreference.com/w/cpp/string/basic_string/stol

so where you might have.

std::string to_string(my_enum);

you might have

my_enum stomy_enum(std::string)

although I would just be verbose about it

my_enum string_to_my_enum(std::string)

or just use streams

std::stringstream ss(my_str);
if(ss >> emun_) //conversion worked

Defining stream operator also allows to use lexical cast from boost;

enum_ = boost::lexical_cast<my_enum>(my_str);
like image 145
111111 Avatar answered May 08 '26 13:05

111111


The C++11 standardlibrary has only stoi et al. for this as far as I know. However if you are ok with using boost (which I'd say is a quasi standard library for c++) you can use boost::lexical_cast. For that to work you just need to define the stream operators operator>> respectively operator<< (for conversion to string) for std::istream (std::ostream) for your own classes.

When not using boost I would still use stream operatos for this, so to get an int from a string I'd do something like the following:

std::string s = ...;
int i;
std::stringstream stream(s);
stream>>i;

Of course you can put that into a more generic function, which will give you functionality similar to boost::lexical_cast.

like image 34
Grizzly Avatar answered May 08 '26 13:05

Grizzly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!