Template metaprogramming – be a good generic programmer
April 18, 2007
Having just had another article published on codeproject, I am reminded yet again how much I miss many of the features of C++ when I’m coding in C#. There’s no denying C# is a very productive language, but C++ techniques I have used and taken for granted just aren’t possible.Generics are a case in point. I constantly feel C# is wanting to hold my hand while crossing the programming road. Generics and C++ templates are not the same thing – the design goals are very different. C# generics are like classes that have a type parameter and everything (pretty much) happens at runtime and C++ templates are just macros that look like classes and it all comes together at compile (and maybe link) time.
If all you do with templates is type safe collections, this is probably not an issue and generics could be considered a safer approach, but it is very limiting. In the SyncInvoker article I use template metaprogramming to achieve code reusability. More accurately I guess this comes under the heading of generic programming so I avoid having the re-write sections of similar code that have minor variations. I guess I’m just lazy.
Template metaprogramming allows the programmer to concentrate on architecture and delegate to the compiler the generation of any implementation required by client code. With template metaprogramming you can create truly generic code – a smaller codebase and better maintainability. However, the syntax and idioms of template metaprogramming are esoteric compared to conventional C++ programming sometimes even the most trivial, template metaprogramming can be very difficult to understand.