Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relation between constexpr and pure functions

Tags:

Am I right, that:

  • Any function defined with constexpr is a pure function, and
  • Any pure function can be and must be defined with constexpr if it's not very expensive for compiler.

And if so, why arent <cmath>'s functions defined with constexpr ?

like image 416
UmmaGumma Avatar asked Mar 28 '11 16:03

UmmaGumma


People also ask

What is the function of 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.

Can constexpr functions call non constexpr functions?

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.

Does constexpr improve performance?

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.

What is the difference between const and constexpr?

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.


2 Answers

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

like image 132
James McNellis Avatar answered Dec 01 '22 21:12

James McNellis


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.

like image 30
James Kanze Avatar answered Dec 01 '22 22:12

James Kanze