Introduction to metaprogramming in C++

This book excerpt from “C++ Templates, Second Edition” explains how to get more functional, more efficient, and more easily maintained code where user-defined computation happens at translation time

Become An Insider


Metaprogramming consists of programming a program. In other words, you lay out code that the programming system executes to generate new code that implements the functionality you really want. Usually, the term metaprogramming implies a reflexive attribute: The metaprogramming component is part of the program for which it generates a bit of code (that is, an additional or different bit of the program).

Why would metaprogramming be desirable? As with most other programming techniques, the goal is to achieve more functionality with less effort, where effort can be measured as code size, maintenance cost, and so forth. What characterizes metaprogramming is that some user-defined computation happens at translation time. The underlying motivation is often performance (things computed at translation time can frequently be optimized away) or interface simplicity (a metaprogram is generally shorter than what it expands to) or both.

Metaprogramming often relies on the concepts of traits and type functions.

The state of modern C++ metaprogramming

C++ metaprogramming techniques evolved over time. Let’s categorize the various approaches to metaprogramming that are in common use in modern C++.

To continue reading this article register now