C++ Core Guidelines: Programming at Compile Time with constexpr

Contents[Show]

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).

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.

  1. 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.
  2. 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.

 constexpr14

The surprise may start now. Let me show you the magic with the Compiler Explorer.

godbolt

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.

TemplateMetaprogrammingVersusConstexprOldI 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.

 

comparison1

 

  •  A constexpr function can have variables and modify them. A metafunction generates a new value.

comparison2

  •  A metafunction uses recursion to simulate a loop.

comparison3

  • 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.

comparison4

  •  Instead of an updated value res, the metafunction generates in each iteration a new value. comparison5

 

 

  • A metafunction has no return statement. It uses value as return value.

comparison6

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.

 

 

Thanks a lot to my Patreon Supporters: Paul Baxter,  Meeting C++, Matt Braun, Avi Lachmish, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Dilettant, Marko, Ramesh Jangama, and G Prvulovic. 

Thanks in particular to:  TakeUpCode 450 60

 

Get your e-book at Leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 600 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Get your interactive course

 

Modern C++ Concurrency in Practice

C++ Standard Library including C++14 & C++17

educative CLibrary

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Runs in the browser
  • 78 code snippets
  • 55 illustrations

Based on my book "The C++ Standard Library" educative.io created an interactive course.

What's Inside?

  • 149 lessons
  • 111 code playgrounds => Runs in the browser
  • 164 code snippets
  • 25 illustrations
Tags: constexpr

Add comment


Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 2759

All 1580495

Currently are 157 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments