>Standard Template Library – readable?

>Since I called some STL code readable, I’ve recieved numerous mails and comments. Fellow Qt/KDE-er dhaumann added his 0.02 EUR to the pile and showed the nicety of template specialization.

Today I thought I’d follow up on some more comments.

First of all, my personal opinion is that C++ is just as readable as most other languages. Even in this case. What can be less readable are the horrendus error messages that one can end up with. I’ve even compiled a small list of error messages and what they really mean in plain English, but this does not – of course – help in ugly template cases. (Yes, the css of digitalfanatics.org is ugly and somewhat broken…)

Back to readability. Even plain English cannot express the two operations that I suggested in a short way. Both cases results in fairly long sentences. Also, try to formally parse and express such sentences with more “interesting” transformation functions.

For every item in the source list, add 42 to it and replace it in the source list.

For every item in the source list, add 42 to it and append it to the end of the destination list.

As the commenter zwabel pointed out, in the put-the-result-in-another-list a simple foreach loop showing the actual operation is good enough and reads better. I agree, but that kind of break my do-everything-on-a-line-thesis.

Titus Brown pointed out that I do too much on a single line. I have to disagree with this – looping and doing something on each item is simple enough.

Then I had lots of suggestions that I say that C++ isn’t functional, but I use a functional style in my example. I’m not sure that I agree. My impression of the STL is that it can perform a number of functions on lists that I’m interested in, for instance.

  • Iterating (for_each)
  • Filtering (remove_if)
  • Searching (find_if)
  • Processing (transform)

To make these operations flexible, they accept a functor – either a predicate or an actual transformation operation. This isn’t really functional programming in my eyes, even if it can be used for functional programming. To me, it is just a set of ways to perform iterations and common tasks.

Anyway, some fun thought that have poped up while discussing this topic. What if we combine these operations with the QtConcurrent framework. I have not tried the framework myself, but I was in Munich and listened to Morten’s presentation of it, and to me it looks like it could be done. What is missing is a nice set of flexible map and filter functions, binders and such goodies that the STL carries.