This is the mail archive of the cygwin-talk mailing list for the cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Why I love C++ so much.


Corinna Vinschen wrote:

Really? Show me an example which isn't much harder to understand than the equivalent C code.

template <class T> std::string foo(const T& x) { std::ostringstream outs; outs << x << and << maybe << other << stuff; return outs.str(); }

(Aside: This looks pointlessly trivial, but it's a simplified version of real code in MySQL++ (http://tangentsoft.net/mysql++/). It would just muddy the waters to talk about the reason MySQL++ does this.)

To do that with C functions (maybe strto*() instead of printf()) you'd have to create a set of template specializations for every T you know about to call the right C function with the right arguments. Any time you add to the list of supported T's, you have to add template specializations.

The main thing IOStreams gives you is type safety. If your types are all portable C primitive types and they're known at compile time, by all means, use C functions for string conversions. IOStreams is nearly useless if you don't use data types that K&R didn't give you.

This includes not just user-defined types, but also unportable ones like the various ways to get a 64-bit integer. Not all C++ compilers fully support C99, so you can't count on having long long. VC++ uses __int64, for instance. As long as the compiler vendor provides operator <<() for the type you want to use, you don't have to introduce more unportable facilities to your code to do something like the T-to-string conversion above. The compiler figures out how to do it for you, and if it changes in the future, you just recompile.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]