Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ overloading operator << for std::string

I'm just now seeing another naive C++ code using sprintf to append C builtins into an array of chars, and I guess enough is enough.

I could help providing with simple, lightweight, appending and non-formatting functions for std::string, but as it would be check-in-ed into the team's common code, I want it to be perfect, so I need some advice on the interface of this feature (i.e. not on the actual implementation).

The following could be possible (I did not test it, it's just a hunch):

  1. Overloading the "+=" operator (probably in another namespace than std or global)
  2. Overloading the "<<" operator (again, in another namespace)
  3. Providing non-operator non-member functions (I guess, again in another namespace)
  4. Another easy solution I did not see?

What would be the pros and the cons of each solution (I have a preference for "+=", or even "<<") ?

Notes

  • the point is not about formatting. If someone wants formatting, C++ streams are good for that. I just want simple, lightweight, one statement/function call appending.
  • The use of another namespace would be because we are not authorized to add code to the std namespace, and I don't want to pollute the global namespace, so, yes, I guess the user would have to add a using namespace SomeNamespace ; as its done for the <utility>'s rel_ops namespace)
  • I'm using std::string which is not able, natively, to handle other types than itself, char and char *. I want to extend that to handle other simple types.
  • Using a stringstream weights too much in term of code (declaring the stream, appending, then retrieving the .str() to put it inside a string, etc. etc.), and the last thing I want is an syntactic sugared inline function instanciating a stringstream at each call). As you can see in the example below, the stringstream solution is too verbose:

.

// sprintf-like code with a char[] buffer:
sprintf(buffer, "%d", myDouble) ;

// stream-like code with a std::string buffer:
std::stringstream str ;
str << myDouble ;
buffer = str.str() ;

// example of desired code with a std::string buffer:
buffer += myDouble ;
like image 643
paercebal Avatar asked Jul 20 '26 00:07

paercebal


1 Answers

I would use ostringstream and stream manipulators to replace sprintf. It's not worth reinventing the wheel.

like image 198
kol Avatar answered Jul 22 '26 15:07

kol



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!