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.

Advertisements

2 Responses to “Template metaprogramming – be a good generic programmer”


  1. Nice article, but I can’t find any template metaprogramming in your article? The SyncCall class takes a template parameter, but you use that only for storing a pointer to the object and a pointer to one of it’s member functions.

  2. FZelle Says:

    There seems to be a small missunderstanding about Generics.
    Generics are not done at runtime, they are a compiletime thing.
    There are alot of things you can do with generics beside typesave collections.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: