1
constexpr PixelType maxVal = std::numeric_limits<PixelType>::max();
constexpr double lnFactor = std::log(maxVal);

Second line gives error C2131: expression did not evaluate to a constant

Why? Can this be rephrased so it compiles?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Dženan
  • 3,329
  • 3
  • 31
  • 44
  • 5
    `std::log` is not `constexpr` – Praetorian Jan 20 '17 at 23:33
  • 1
    There are many ways to calculate logarithms, but not all of them can be easily done at time of compilation (which is the basic premise behind `constexpr`). Since the C++ standard can not force library writers to use variants that can be evaluated at compile time, it can't be turned into a `constexpr` function. So you simply can't use it to calculate logarithms at compile-time. – Some programmer dude Jan 20 '17 at 23:36
  • 1
    Does MSVC have a compiler intrinsics for it? (....) https://www.reddit.com/r/cpp/comments/3k897k/constexpr_of_natural_log_in_c11/ https://hbfs.wordpress.com/2016/03/22/log2-with-c-metaprogramming/ – Karoly Horvath Jan 20 '17 at 23:40
  • 1
    Maybe you can use this: If `PixelType` is an unsigned integral type, `log(maxVal + 1) == log(2) * `, or approximately `0.69314718056 * sizeof(PixelType) * 8`. – Christopher Oicles Jan 21 '17 at 00:17
  • That's a good and easy alternative @ChristopherOicles – Dženan Jan 21 '17 at 00:31

1 Answers1

0

The reason why you get a compile error is that std::log is not constexpr.

I am not aware of a portable way to make it work with constexpr, but GCC has __builtin_log that works in constexpr context (godbolt):

constexpr double lnFactor = __builtin_log(42.0);
vitaut
  • 49,672
  • 25
  • 199
  • 336