Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't standard library common mathematical functions "constant expressions"?

For some reason, clang++ (but not g++) complains about:

constexpr double invdecayf1m(double x) {
  return -log1p(-x);
}

telling me that

non-constexpr function 'log1p' cannot be used in a constant expression
  return -log1p(-x);

Why aren't common mathematical functions declared in <cmath> all declared to be “constexpr functions”?

like image 950
Neil G Avatar asked Jan 23 '14 08:01

Neil G


3 Answers

I think the only reason is nobody wrote a proposal to make them constexpr. In general it is possible as they are pure functions. Implementations can use compiler intrinsics to implement them for theier lib, so no "real" implementation is needed. But without proposal you can not count on constexpr implementations of these features.

like image 53
Jan Herrmann Avatar answered Sep 30 '22 15:09

Jan Herrmann


The math library as implied in the name <cmath> comes from c and was written when constexpr was not even an idea.

In order for most functions to be constexpr you would have to rewrite the whole library in a constexpr way.

like image 33
Drax Avatar answered Sep 30 '22 14:09

Drax


The answer is in the link you posted :

 the function body must be either deleted or defaulted or contain only
 the following:   

....
exactly one return statement that contains only literal values, constexpr variables and functions.

The functions there are not that simple. As a matter of fact, they are quite complex, and not possible to implement as a single return statement. Trigonometric, logarithmic and hyperbolic functions are quite complex, and difficult to implement as constexpr functions.

like image 23
BЈовић Avatar answered Sep 30 '22 16:09

BЈовић