1

I am trying to do something like:

#include <cmath>

template <unsigned A, unsigned B>
struct fu {
    constexpr unsigned long power_A_of_B = std::pow(A, B);
};

But the compiler gives error because pow() is not constexpr.

Why are math functions in header <cmath> not constexpr? For example, log(), log2(), pow(), abs() and fmax() are not constexpr but others in <algorithm> are, such as max(), min() and `clamp()'.

Arjonais
  • 563
  • 2
  • 17
  • u can make yours – asmmo Aug 04 '20 at 14:49
  • `std::is_constant_evaluated` to do it yourself :) – DeiDei Aug 04 '20 at 14:51
  • 1
    The answer is not some deep technical reason, just that "the committee are only human, they didn't get to it yet". Not sure of the current state of [these proposals](https://deathandthepenguinblog.wordpress.com/2019/02/17/more-constexpr-in-c20/). – BoBTFish Aug 04 '20 at 14:52
  • 3
    Possible duplicate: [Constexpr Math Functions](https://stackoverflow.com/q/17347935/1782792). In short, many `cmath` functions set `errno`, which is a side effect and therefore non constexpr. – jdehesa Aug 04 '20 at 14:52

1 Answers1

3

Why are math functions in header not constexpr?

Reason is well hidden in documentation of std::pow:

std::pow, std::powf, std::powl - cppreference.com

Error handling

Errors are reported as specified in math_errhandling.

See documentation of math_errhandling.

Now how this macro could be handled in a constexpr?

So whole problem is maintaining compatibility with old specification.

The only possible solution is used alternative implementations. I've found something like this, didn't tested it, but looks promising. Found here.

Marek R
  • 32,568
  • 6
  • 55
  • 140