Yes, you read it correctly. Today, I write about template metaprogramming, programming with types and not values.
The introduction to template metaprogramming in the guidelines ends uniquely: “The syntax and techniques needed are pretty horrendous.”. In accordance, the rules are primarily about dont’s and do not provide much content:
- T.120: Use template metaprogramming only when you really need to
- T.121: Use template metaprogramming primarily to emulate concepts
- T.122: Use templates (usually template aliases) to compute types at compile time
- T.123: Use
constexprfunctions to compute values at compile time
- T.124: Prefer to use standard-library TMP facilities
- T.125: If you need to go beyond the standard-library TMP facilities, use an existing library
Honestly, I don’t think template metaprogramming is so horrendous, but the syntax still has a lot of potential.
Let me try to demystify template metaprogramming and write about programming at compile time in general. During this introduction to programming at compile time, I explicitly write about type-traits (T.124: Prefer to use standard-library TMP facilities) and constexpr functions (T.123: Use
constexpr functions to compute values at compile time) and implicitly refer to the other rules. Here is my plan:
I introduce template metaprogramming, show how the type-traits library allows you to use template metaprogramming in a well-structured and portable way, and how you can use constexpr functions to replace template metaprogramming magic with ordinary functions.
How it all started
1994 presented Erwin Unruh at a C++ committee meeting, a program that didn’t compile. Here is probably the most famous program that was never compiled.
Erwin Unruh used the Metaware Compilers, but the program is not valid for C++ anymore. A newer variant from the author is here. Okay, why is this program so famous? Let’s have a look at the error messages.
I highlighted the important parts in red. I think you see the pattern. The program calculates at compile time the first 30 prime numbers. This means template instantiation can be used to do math at compile time. It is even better. Template metaprogramming is Turing-complete, and can, therefore, be used to solve any computational problem. (Of course, Turing completeness holds only in theory for template metaprogramming because the recursion depth (at least 1024 with C++11) and the length of the names generated during template instantiation provide some limitations.)
How does the magic work?
Let me start traditional.
Calculating at Compile Time
Calculating the factorial of a number is the “Hello World” of template metaprogramming.
The call factorial<5>::value in line (1) causes the instantiation of the primary or general template in line (2). During this instantiation, Factorial<4>::value will be instantiated. This recursion will end if the fully specialised class template Factorial<1> kicks in in line (3). Maybe, you like it more pictorial.
Here is the output of the program:
Damn, I almost forgot to prove that the values were calculated at compile time. Here we are with the Compiler Explorer. For simplicity reasons, I only provide a screenshot of the main program and the corresponding assembler instructions.
The first yellow line and the first purple line show it. The factorials of 5 and 10 are just constants and were calculated during compile time.
The factorial program is friendly but not idiomatic for template metaprogramming.
Manipulating Types at Compile Time
Manipulating types at compile time is typically for template metaprogramming. If you don’t believe me, study std::move. Here is what std::move is conceptionally doing:
Okay. std::move takes an argument arg, deduces the type (decltype(arg)) from it, removes the reference (remove_reverence), and casts it to a rvalue reference (static_cast<…>::type&&>). In essence, this means that std::move returns always a rvalue reference type and, therefore, move semantic can kick it.
How does std::remove_reference from the type-traits library work? Here is a code snippet removing constness from its argument.
I implemented removeConst the way std::remove_const is probably implemented in the type-traits library. std::is_same from the type-traits library helps me to decide at compile-time if both types are the same. In the case of removeConst<int>, the first or general class template kicks in; in the case of removeConst<const int>, the partial specialization for const T applies. The critical observation is that both class templates return the underlying type in line (1), and the constness is removed.
In the next post, I will continue my introduction to programming at compile time. This means, in particular, that I will compare functions and metafunctions before I come to the type-traits library.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
|My special thanks to SHAVEDYAKS|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,