Am I right, that:
constexpr
is a pure function, andconstexpr
if it's not very expensive for compiler.And if so, why arent <cmath>
's functions defined with constexpr
?
A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations. And when a value is computed at compile time instead of run time, it helps your program run faster and use less memory.
A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.
Understanding constexpr Specifier in C++ constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time.
The principal difference between const and constexpr is the time when their initialization values are known (evaluated). While the values of const variables can be evaluated at both compile time and runtime, constexpr are always evaluated at compile time.
To add to what others have said, consider the following constexpr
function template:
template <typename T> constexpr T add(T x, T y) { return x + y; }
This constexpr
function template is usable in a constant expression in some cases (e.g., where T
is int
) but not in others (e.g., where T
is a class type with an operator+
overload that is not declared constexpr
).
constexpr
does not mean that the function is always usable in a constant expression, it means that the function may be usable in a constant expression.
(There are similar examples involving nontemplate functions.)
In addition to the previous answers: constexpr on a function restricts its implementation greatly: its body must be visible to the compiler (inline), and must consist only of a single return statement. I'd be surprised if you could implement sqrt() or sin() correctly and still meet that last condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With