If you declare a variable as constexpr the compiler will evaluate them at compile time. This holds not only true for built-in types but also for instantiations of user-defined types. There are a few serious restrictions for objects to evaluate at compile time.
To make it easier, I will use built-in types like bool, char, int, and double. I will call the remaining data types user-defined data types. These are, for example, std::string, types from the C++ library, and user-defined data types. User-defined types typically hold built-in types.
By using the keyword constexpr the variable becomes a constant expression.
Therefore, I can use the variable in contexts requiring constant expression. For example, if I want to define the size of an array. This has to be done at compile time.
For the declaration of constexpr variable, you have to keep a few rules in mind.
- is implicitly const.
- has to be initialized.
- requires a constant expression for initialization.
The rule makes sense. If I evaluate a variable at compile time, the variable can only depend on values that can be evaluated at compile time.
The invocation of the constructor creates the objects. The constructor has a few special rules.
The class MyDistance from the post Constant expressions with constexpr fulfills all requirements to be initialized at compile time. But what are the requirements?
A constexpr constructor can only be invoked with constant expressions.
- can not use exception handling.
- has to be declared as default or delete or the function body must be empty (C++11).
The constexpr user-defined type
- can not have virtual base classes.
- requires that each base object and each non-static member has to be initialized in the initialization list of the constructor or directly in the class body. Consequently, it holds that each used constructor (e.g of a base class) has to be constexpr constructor and that the applied initializers have to be constant expressions.
Sorry, but the details are even harder: cppreference.com. To make the theory obvious I define the class MyInt. MyInt shows the just mentioned points. The class has in addition constexpr methods. There are special rules for constexpr methods and functions. These rules will follow in the next post, so we can concentrate in this post on the essentials about variables and user-defined types.
The class MyInt has three constructors. A constexpr default constructor (line 8) and a constructor taking two (line 9) and taking one argument (line 10). The constructor with two arguments is a constexpr constructor. Therefore, its body is empty. This holds not true for the non-constexpr constructor with one argument. The definition goes on with a defaulted copy-constructor (line 15) and a deleted move-constructor (line 16). Additionally, the class has two methods, but only the method getSum is a const expression. I can only define the variables myVal1 and myVal2 (lines 26 and 27) in two ways if I want to use them in constexpr objects. At first, I can initialize them in the initialization list of the constructor (line 9); second, I can initialize them in the class body (lines 26 and 27). The initialization in the initialization list of the constructor has a higher priority. It’s not allowed to define both variables in the body of the constructor (lines 11 and 12).
To put the theory to practice, here is the output of the program.
The program shows a few special points:
- You can use a constexpr constructor at run time. Of course, there is no constant expression (line 36 and line 46).
- If you declare a non-constant expression as constexpr, you will get a compiler error (lines 52 and 57).
- constexpr constructors can coexist with non-constexpr constructors. The same holds for the methods of a class.
The key observation is: A constexpr object can only use constexpr methods.
But stop. What’s the story about the two last lines, 62 and 63, in the main function?
Quite straightforward. They prove that the call myIntConst3.getSum() is performed at compile time.
At first, C++ requires that an array’s size be a constant expression. Second, static_assert evaluates its expression at compile time. If not, static_assert will not compile.
If I replace line 63
with the line
, I will get a compiler error.
I think you know it already. In the next post, I will write about contexpr functions. They have with C++11 a lot of restrictions that will almost disappear with C++14. constexpr functions in C++14 feel almost like normal functions. Of course, my points about functions will also hold for methods of classes.
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, and Marco Parri Empoli.
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|
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,