constexpr specifier
Using the constexpr specifier, we declare that it is possible to evaluate variables and functions at compile time. There are limitations to what can be evaluated at compile time. A constexpr variable must meet the following requirements:
- It needs to be of a
literaltype, any of the following:- Scalar types such as arithmetic types, enumerations, and pointers
- Reference types
- An array of
literaltypes
- Classes that meet specific requirements (such as a trivial
constexprdestructor, all of its non-static data members areliteraltypes, or at least oneconstexprconstructor). - It must be immediately initialized.
- The entire expression of its initialization needs to be a constant expression.
Let’s go through the following example to better understand the requirements for constexpr variables:
#include <cmath>
int main () {
constexpr int ret = round(sin(3.14));
return...