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
literal
type, any of the following:- Scalar types such as arithmetic types, enumerations, and pointers
- Reference types
- An array of
literal
types
- Classes that meet specific requirements (such as a trivial
constexpr
destruct
or, all of its non-static data members areliteral
types, or at least oneconstexpr
construct
or). - 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...