Template Metaprogramming

Template Metaprogramming is programming at compile time. However, what does template metaprogramming have in common with the type-traits library? As it turns out, quite a lot! The type-traits library is pure template metaprogramming enclosed in a library.

Applications of Template Metaprogramming

  • Programming at compile time.
  • Programming with types such as double or int and not with values such as 5.5 or 5.
  • Compiler instantiates the templates and generates C++ code.

Type Traits: Goals

The type-traits library requires the following header:

#include <type_traits>

If you look carefully, you will see that type-traits have a big optimization potential. In the first step, the type-traits analyze the code at the compile time, and in the second step, they optimize the code based on that analysis. How is that possible? Depending on the type of the variable, a faster variant of an algorithm will be chosen.

Optimization

  • Optimised version of std::copy, std::fill, or std::equal is used so the algorithms can work on memory blocks.

Correctness

  • Type checks will be performed at compile time
  • Together with static_assert, the type information defines the requirements for the code.

Get hands-on with 1000+ tech skills courses.