Metaprogramming and .NET and Java.

After starting a dive into C++ metaprogramming, I decided to satisfy my curiosity about .NET generics. I’ve used them, very much as I’ve used C++ templates, to create generic functions and classes. As with C++ I’ve never yet found reason to try the more complex things that metaprogramming pursues.

I was very unimpressed with the java implementation of Generics. Their ‘type erasure’ approach favors backward compatibility with pre-generics code but breaks things that you’d expect to work. The worst issue I’ve encountered relates to method overloading…since type erasure changes <code>ArrayList<Foo></code> to a list of objects in compiled form the VM has no way to distinguish between <code>Process(ArrayList<CReceipts>)</code> and <code>Process(ArrayList<CClaims>)</code>.  This tends to force the type into the method name and breaks things that in C++ would be easy to do with templates (in addition to cluttering up code and causing short term consternation as otherwise reasonable overloads generate strange compile time errors).

The C# approach seems to be closer to the C++ template facility. Some of the more preprocessor-like stuff is missing (template arguments as numeric values for example) but the basics for metaprogramming seem to be mostly there. The language definitely seems to support overloading on generic types and with the availability of delegates I’d expect it to support generic methods operating on items with compatible signatures (as with the Process function proposed above). I’ll see what the book on .NET metaprogramming has to say when it comes in, but as with most things .NET (compared to the java equivalent) I’m finding this to be well designed with an eye towards expressiveness and future value.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.