Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toString function or (std::string) cast overload in c++

Tags:

c++

oop

c++11

c++14

I am writing a class which I want to be converted into a string.

Should I do it like this:

std::string toString() const;

Or like this:

operator std::string() const;

What way is more accepted?

like image 536
Tom Gringauz Avatar asked Dec 17 '16 14:12

Tom Gringauz


1 Answers

The classes that have a "string" representation in the standard library (like std::stringstream, for example) use .str() as a member function to return a text. If you want to be able to use your class into generic code as well, better to use the same convention (toString is "Javanese" and ToString "Sharpish").

About the use of a conversion operator, that makes sense only if your class is specifically designed to interwork with strings in string expressions (converting to a string is in fact a "promotion", like a int becoming long implicitly).

If your class "demotes" into a string (loses information in doing so), better to have the cast operator explicit (explicit operator std::string() const).

If it is unrelated with string semantics, and just has to be occasionally converted, consider explicitly named functions.

Note that, if a is a variable, the semantics you have to think about its usage are:

a.str();       // invoking a member function 
               // mimics std::stringstream, and std::match_results 

to_string(a);  // by means of a free function 
               // mimics number-to-text conversions 

std::string(a) // by means of an explicit cast operator 
               // mimics std::string construction

If your class has nothing to do with strings, but only has to participate in I/O, then consider the idea not to convert to string, but to write to a stream, by means of a...

friend std::ostream& operator<<(std::ostream& stream, const yourclass& yourclass)

so that you can do...

std::cout << a;

std::stringstream ss;
ss << a;   // this makes a-to-text, even respecting locale informations.

...maybe even without the need to allocate any string-related memory.

like image 58
Emilio Garavaglia Avatar answered Nov 09 '22 03:11

Emilio Garavaglia