You are viewing...

Dabbling in C++, Template Metaprogramming Overview

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

DISCLAIMER: All views are considered my own and you should not draw any conclusions on associates.

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.

Links

  1. https://akrzemi1.wordpress.com/2012/03/19/meta-functions-in-c11
  2. http://blog.biicode.com/template-metaprogramming-with-modern-cpp-introduction/index.html
  3. http://www.boost.org/doc/libs/1_61_0/libs/mpl/doc/tutorial/tutorial-metafunctions.html
You just read "Dabbling in C++, Template Metaprogramming Overview". Please share if you liked it!
You can read more recent posts here.