Note: If you have not read the previous post on understanding templates, you will definitely struggle to understand template metaprogramming. Read understanding templates first then come back when you are ready to tackle C++ Template metaprogramming in Practice. If you are a complete beginner to C++ or any programming language, please do not read this is a very difficult and advanced topic. 

What is C++ Template Metaprogramming in Practice?

We all know that when we are writing a program, we are coding a sequence of instructions that creates and modifies data. What Template metaprogramming does is that metaprogramming is a sequence of instructions that modifies and creates programs. C++ templates that have been created can be customized at compile time with the help of metaprogramming.

meta programming diagram 1

When we were introduced to C++ templates, there were two major types of templates which were template functions and class templates. As the name says, a template function is not a function at all and the same goes for class templates. They are simply used as a template to generate functions and classes. What you just read sounds really confusing. Let’s go down deeper with this concept. When you are using templates and you are running the code, it will generate different data types. Without being rewritten every time for each one as a template that will be reused.

An example would be the std::vector as it is actually not a class. It is a template built in the C++ Standard template library. It applies C++ templates to generate the correct vector class for each type of data. When std::vector is used, the compiler will generate the code for a vector of doubles and vice versa if integers were used.

Metafunctions are the basic unit of metaprogramming. Meta functions is simply a function working with types in which the entities can be manipulated.

Let’s look at an example of a simple metafunction

metaprogramming example

In line 10, the template throw_balls is the metafunction that takes a type and throws away all the balls. Metaprogramming is used to generate code automatically. This is only a very brief example of template metaprogramming. They go deeper into design patterns, code optimization, and many other advanced programming topics

Share this post