Introduction to template metaprogramming
When writing regular C++ code, it is eventually transformed to machine code. Metaprogramming, on the other hand, is code that transforms itself into regular C++ code. When using metaprogramming, it is important to remember that its main use case is to make great libraries and, thereby, hide complex constructs/optimizations from the user code. So, remember that howsoever complex the interior of the metacode may be, it's important to hide it behind a good interface so that the user code base is easy to read and use.
In its simplest and most common form, template metaprogramming in C++ is used to generate functions, values, and classes that accept different types.
Let's take a look at a simple pow()
function and a Rectangle
class. By using a template parameter, the rectangle can be used with any integer or floating point type. Without templates, the programmer would have to create a separate function/class for every base type.
The compiler then compiles...