constexpr

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

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

constexpr

Finally, we are at the peak. This is more than a picture.

constexpr

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?

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

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

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

    User-defined types

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

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

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

     

    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 specialization of a template to end a loop. Additionally, a metafunction uses partial or full specialization 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 the value as a return value.

    comparison6

    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 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 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, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, 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, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

    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

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    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++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *