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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With