Programming at Compile Time with constexpr
This is a cross-post from www.ModernesCpp.com.
My mini-series about programming at compile time started with template metaprogramming, continued with the type-traits library, and ends today with constant expressions (constexpr).
Finally, we are at the peak. This is more than a picture.
constexpr
constexpr allow you to explicitly program at compile time with the typical C++-Syntax. 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?
Advantages
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.
Three Forms
Variables
- are implicit const.
- have to be initialized by a constant expression.
constexpr double pi = 3.14;
Functions
constexpr functions in C++14 are quite comfortable. They can
- invoke other constexpr functions.
- can have variables which have to be initialised by a constant expression.
- can can conditional expressions or loops.
- are implicit inline.
- cannot have static or thread_local data.
User-defined types
- has 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 quite simple. For 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 optimisation level if a constexpr functions 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 which is evaluated at compile time. This can be a static_assert expression such as with the type-traits library or the initialisation 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.
// constexpr14.cpp
#include <iostream>
constexpr auto gcd(int a, int b){
while (b != 0){
auto t= b;
b= a % b;
a= t;
}
return a;
}
int main(){
std::cout << std::endl;
constexpr int i= gcd(11,121); // (1)
int a= 11;
int b= 121;
int j= gcd(a,b); // (2)
std::cout << "gcd(11,121): " << i << std::endl;
std::cout << "gcd(a,b): " << j << std::endl;
std::cout << std::endl;
}
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 screenshot). In contrast, line (2) is a function call: call gcd(int, int) (line 41 in the screenshot.
Finally, I come 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 a 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 which have the potential to run at compile time. Therefore, they can only accept values.
- There is not 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, you can have the first Defintion of Functional Programming or more details Functional. Here are the bullet points:
- Instead of modifying a value you return each time a new value in template metaprogramming.
- Controlling a for-loop by incrementing a variable such as i is not possible at compile time: for (int i; i <= 10; ++i). Template metaprogramming, therefore, replaces loops with recursion.
- You replace conditional execution with template specialisation.
Admittedly, this comparison was quite 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 functions 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 specialisation of a template to end a loop. Additionally, a metafunction uses partial or full specialisation 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 value as return value.
Advantages of constexpr functions
Besides the advantages that constexpr functions are more comfortable to write and to maintain and can run at compile time and runtime, they have an additional advantage. Here it is:
constexpr double average(double fir , double sec){
return (fir + sec) / 2;
}
int main(){
constexpr double res = average(2, 3);
}
constexpr functions can deal with floating point numbers. Template metaprogramming accepts only integral numbers.
What's next?
This post ends my detour to programming at compile time. Next time, I write about the few remaining rules to templates.