Saturday 7 March 2009

Stupid C++ Tricks

I recently came across this C++ Soup post, which demonstrates some cute C++ tricks. Now by cute, I mean stupid, similar to Dave Letterman’s segment “stupid pet tricks” (you can google that if you’ve never seen this). It’s a useless language exercise with little practical application except to show how obfuscated one can make C++. Are there any benefit to these tricks? Lets explore.

Now all C++ programmers do this (myself included) just to see if they understand template programming, so keep in mind that this is NOT a critique of this particular author, who I’m sure is a C++ Ninja. It’s just a recent example that triggered this rant. No, just have a look at half the boost libraries to see this thinking taken to the extreme. Or even the C++ standard library; does anyone really use the cumbersome std::for_each function or any of that bind stuff? They all feel like they’re unfinished ideas: they’re onto something, but they’re not quite there yet.

These (what I’m calling) C++ tricks are often segments of templated C++ code that push generic programming to solve some kind of basic problem, that is typically solved using simpler (but more verbose) code. A trick author is often amazed (and proud) at how small or flexible the code is, but hopefully realizes that the amount of work or expertise required to make the trick outweighs most benefits. The code is then shelved. Lets cut this silliness out.

Furthermore, most application developers will steer clear (or be ignorant) of such tricks, and popular C++ libraries do well to not require such expertise from their users.

Is there any benefit to these tricks? Yes, only to show what could be possible with C++.

C++ is an extremely powerful language, giving you compile time dynamic/generic programming with no loss of runtime performance. No other language does this so fully and completely, and C++ is still the only language option in many demanding areas.

However, the language needs to grow, and it needs to grow fast. We must look at what these tricks are trying to do, and then think how we can change the language to do the same thing in a sane, logical fashion. C++0x is working on this with lambdas, type inference, better error reporting and some other niceties. But we needed these features yesterday, and get people using them. Lets steal more features from other languages. Lets turn up the meta programming capabilities so we can extend the language without meta-compilers and preprocessors, which until now provide the bulk of the useful new language extensions.

There is no reason why C++ can’t offer easy to use and powerful compile-time dynamic programming, resulting in code that looks like a dynamic scripting language, but with safer types and kick-ass performance, memory use and code size.

0 comments: