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 allows 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 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, 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: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner,  Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Avi Kohn, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, Sudhakar Balagurusamy, lennonli, and Pramod Tikare Muralidhara.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, and Dendi Suhubdy

 

Seminars

I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.

Bookable (Online)

Deutsch

English

Standard Seminars 

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmSmall

Tags: constexpr

My Newest E-Books

Course: Modern C++ Concurrency in Practice

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

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 624

Yesterday 7813

Week 17011

Month 175442

All 5044756

Currently are 121 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments