C++ Template metaprogramming

Note: If you have not read 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 template metaprogramming. If you are a complete beginner to C++ or any programming language, please do not read this is a very difficult and advance topic. 

What is C++ Template Metaprogramming?

We all know that when we are writing a program, we are coding a sequence of instructions which creates and modifies data. The simplest way to describe what Template metaprogramming does, is that metaprogramming is a sequence of instructions which 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 which applies C++ templates to generate the correct vector class for each type of data type being used. 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 which the entities can be manipulated.

Lets’s look at an example of a simple metafunction

metaprogramming example

In line 10, the template throw_balls is the metafunction which takes a type and throws away all the balls. The key concept to take away from this example is metaprogramming is used to generate code automatically. This is only a very brief example of template metaprogramming as they go deeper into design patterns, code optimization and many other advanced programming topics.

Share this post