Smalltalk vs C# vs C++ - A generic template story
I got thrown in at the deep end at work recently. I was moved to work on a piece of software which was all written in C++. So I've been spending some time on the dark side.
I'm happy to say that all that power (complexity) has left a bad taste in my mouth. It's made me cling to my Smalltalk even more tightly, however I have to say C++ does have some pretty cool stuff going for it. The "simple" operator overloading (opposed to C#) ans also C++ templates.
I knew what C# generics were before I knew what C++ templates were. Although I knew that generics were based on templates, I'd never actually done anything in C++, so it was a kind of meaningless comment to me.
This post came about when I tried to write a simple Smalltalk like Interval class in C# and generics. I succeeded, but it required me to define two a generic Interval<T> class, two interfaces, one for doing the step addition, and one for doing the comparison between the current and end positions, and two implementations of the Additiona/LessThan operator interfaces. It worked, but damn it wasn't straight forward. I've put the code here if you're interested. I did two versions; One using anonymous methods, and one using interfaces. Interval.cs. This is not the "One True Way" (I could have used an enumerator and yielded each value, a new feature in C# 2.0.. anyways!) .. as you can see from the code, it's crufty. There is a lot of code to write for what should be something quite simple.
Next I wrote up a C++ version. Interval.cpp. Guess what, much simpler!
Finally here is a pseudo-Smalltalk version, because it isn't proper chunk format (I wrote it in notepad) which does the same thing. Interval.st.
One comment on this: I think it is the only time you'll see C++ code that is close to Smalltalk, and has the same requirements on the object the Interval steps over: that the object implements the messages #<= and #+. The issue with C# is that C# CAN NOT use operators with generics. I didn't realise why there was an uproar about this when generics for C# was first announced, but now I understand.
BTW, if you've never actually used Smalltalk before, there is already a very rich and useful Interval class which implements the collection protocol, so you can actually do things like iterate over it using #collect: #select: and so on. Very nice indeed. There is no such equivelent in the static world.
James has made a couple of posts recently on the issues with generics in C# and Java. Every time I start to write any generic code in C#, I wonder why people can make comments about Smalltalk being the train that "rusted at the station", when clearly that's just not possible when the Smalltalk train was made out of nice shiny stainless steel.
Update: Oops. Fixed the broken links