Introduction to template metaprogramming
When writing regular C++ code, it is eventually transformed into machine code. Metaprogramming, on the other hand, allows us to write code that transforms itself into regular C++ code. In a more general sense, metaprogramming is a technique where we write code that transforms or generates some other code. By using metaprogramming, we can avoid duplicating code that only differs slightly based on the data types we use, or we can minimize runtime costs by precomputing values that can be known before the final program executes. There is nothing that stops us from generating C++ code by using other languages. We could, for example, do metaprogramming by using preprocessor macros extensively or writing a Python script that generates or modifies C++ files for us:
Figure 8.1: A metaprogram generates regular C++ code that will later be compiled into machine code
Even though we could use any language to produce regular code, with C++, we...