I want to compute a lookup table at compile time for a mathematical function in a given range and then retrieve the values ββfrom the table at runtime. My code is as follows:
#include <iostream>
#include <cmath>
template<int size>
class LookupTable {
public:
constexpr LookupTable(double xMin, double xMax) : array(), xMin(xMin), xMax(xMax), dx((xMax - xMin) / (size - 1)) {
for(auto i = 0; i < size; ++i)
array[i] = exp(xMin + i * dx);
}
constexpr double operator()(double x) const {
return array[std::min(std::max(static_cast<int>((x - xMin) / dx), 0), size-1)];
}
private:
double array[size];
double xMin;
double xMax;
double dx;
};
int main() {
const double x = 0.5;
constexpr LookupTable<10000> table(0.0, 1.0);
std::cout << "f(x) = " << table(x) << std::endl;
std::cout << "f(x) = " << LookupTable<10000>(0.0, 1.0)(x) << std::endl;
return 0;
}
The code compiles and runs on gcc 5.1 and higher, but not on Clang 3.8. Clang: constexpr variable 'table' error messages must be initialized with a constant expression, and the non-constexpr 'exp' function cannot be used in a constant expression.
When I remove constexpr in:
constexpr LookupTable<10000> table(0.0, 1.0);
then the code compiles and runs on Clang.
My questions:
- What is the meaning of the "exp" function error message cannot be used in a constant expression "? And is there a workaround?
- , LookupTable < 10000 > (0.0, 1.0); constexpr, ?
- , .
- . , ?