My mini-series about programming at compile time started with template metaprogramming, continued with the type-traits library, and ended today with constant expressions (constexpr).
Finally, we are at the peak. This is more than a picture.
constexpr allows you to program at compile time with the typical C++-Syntax explicitly. The focus of this post is not to provide you with all details to constexpr but to compare template metaprogramming with constexpr functions. Before I compare both techniques, I will give you a short overview of constexpr. If this is too short, read my previous posts about constexpr. What are the advantages of constant expressions?
A constant expression
- can be evaluated at compile time.
- give the compiler deep insight into the code.
- are implicitly thread-safe.
- can be constructed in the read-only memory (ROM-able).
Constant expressions with constexpr can have three forms.
- are implicit const.
- have to be initialized by a constant expression.
constexpr functions in C++14 are quite comfortable. They can
- invoke other constexpr functions.
- can have variables that have to be initialized by a constant expression.
- can conditional expressions or loops.
- are implicit inline.
- cannot have static or thread_local data.
- have to have a constructor, which is a constant expression.
- cannot have virtual functions.
- cannot have a virtual base class.
The rules for constexpr functions or methods are pretty simple. In short, I call both functions.
constexpr functions can only depend on functionality which is a constant expression. Being a constexpr function does not mean that the function is executed at compile time. It says that the function has the potential to run at compile time. A constexpr function can also run a runtime. It’s often a question of the compiler and the optimization level if a constexpr function runs at compile time or runtime. There are two contexts in which a constexpr function func has to run at compile time.
- The constexpr function is executed in a context evaluated at compile time. This can be a static_assert expression, such as with the type-traits library or the initialization of a C-array.
- The value of a constexpr function is requested during compile time with constexpr: constexpr auto res = func(5);
Here is a small example of the theory. The program constexpr14.cpp calculates the greates common divisor of two numbers.
Line (1) calculates the result i at compile time, and line (2) j at runtime. The compiler would complain when I declare j as constexpr: constexpr int j = gcd(a, b). The problem would be that int’s a and b are not constant expressions.
The output of the program should not surprise you.
The surprise may start now. Let me show you the magic with the Compiler Explorer.
Line (1) in the program constexpr14.cpp boils down to the constant 11 in the following expression: mov DWORD PTR[rbp-4], 11 (line 33 in the screenshot). In contrast, line (2) is a function call: call gcd(int, int) (line 41 in the screenshot.
Finally, I came to my main point.
Template Metaprogramming versus constexpr Functions
Here is the big picture.
I want to add a few remarks to my table.
- A template metaprogram runs at compile, but constexpr functions (see the constexpr14.cpp example) can run at compile time or runtime.
- Arguments of a template (template metaprogram) can be types and values. To be more specific, a template can take types (std::vector<int>), values (std::array<int, 5>), and even templates (std::stack<int, std::vector<int>>). constexpr functions are just functions that have the potential to run at compile time. Therefore, they can only accept values.
- There is no state at compile time and, therefore, no modification. This means template metaprogramming is programming in a pure functional style. What? If you want to know what pure functional means, read the first Definition of Functional Programming or have more details here: Functional. These are the bullet points:
- Instead of modifying a value, you return a new value in template metaprogramming each time.
- Controlling a for-loop by incrementing a variable such as i is impossible at compile time: for (int i; i <= 10; ++i). Template metaprogramming, therefore, replaces loops with recursion.
- You replace conditional execution with template specialization.
Admittedly, this comparison was relatively concise. A pictural comparison of a metafunction and a constexpr function should answer the open questions. Both functions calculate the factorial of a number.
- The function arguments of a constexpr function correspond to template arguments of a metafunction.
- A constexpr function can have variables and modify them. A metafunction generates a new value.
- A metafunction uses recursion to simulate a loop.
- Instead of an end condition, a metafunction uses a full specialization of a template to end a loop. Additionally, a metafunction uses partial or full specialization to perform conditional execution such as if statements.
- Instead of an updated value res, the metafunction generates in each iteration a new value.
- A metafunction has no return statement. It uses the value as a return value.
Advantages of constexpr functions
Besides the advantages that constexpr functions are more comfortable to write and maintain and can run at compile-time and runtime, they have an additional advantage. Here it is:
constexpr functions can deal with floating-point numbers. Template metaprogramming accepts only integral numbers.
This post ends my detour to programming at compile time. Next time, I will write about the few remaining rules to templates.
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,