You are viewing...

Dabbling in C++, Template Metaprogramming Overview

Updated on September 08, 2016 at the 14th hour
Posted under:

DISCLAIMER: Expressed views on this blog are my own.

When I used to hangout in IRC gamedev channels, template metaprogramming was that arcane and cryptic thing to me... It still is. Why would anyone use it anyway? How does it make life easier for me? The truth appears to be don't use it unless you have a really good reason, but that should not stop anyone from learning about it in case it is encountered while reading other code.

So why use it? If you've used Java, then you know ArrayList<Integer> is a dynamic collection of Integer objects. The equivalent in C++ is std::vector<int>. In both languages, you can now add and remove integers from a list. Useful and makes my life easier. Simple use case for generics/templating.

C++ templates also support the idea of dynamically generating templates at compile time and that's where the scariness, power and underuse of metaprogramming lies. Some say it is a functional language inside of C++. I think tutorials set the reader's mindset of where template metaprogramming is used.

Lots of tutorials show these impractical ways of dynamic generation of templates such as calculating a factorial... >_> Seriously, way to set the example... How about generating templates for a two, three or ten tuple? or templates that doe type checking of unchecked types? Can we build expression or parser tokens? Those are more useful examples than the crappy factorial which gives me zero idea on why metaprogramming may be useful in my everyday or scientific code. I implore you as a reader to comment of other blog posts where crappy examples are being used.

As for tutorials, I think the first link is an example of crappy tutorial. The second link below may be more helpful to get introduced to metaprogramming. The third one is more involved with the number of tutorials and the fact that it assumes you already know about metaprogramming and want to use it in a way that is practical.


You just read "Dabbling in C++, Template Metaprogramming Overview". Please share if you liked it!
You can read more recent posts here.