I am trying to implement Gauss-Legendre quadrature, and I want a templated function that takes the number of points as a template parameter. Right now I have this:
template<int number_of_quadrature_points>
double gaussian_quadrature_integral_core(double (*f)(double), double from, double to){
double scaling_factor = (to-from)/2;
double average_factor = (from+to)/2;
std::array<double, number_of_quadrature_points> factors;
std::array<double, number_of_quadrature_points> points;
if constexpr(number_of_quadrature_points == 2){
factors = {1, 1};
points = {-1.0/sqrt(3), 1.0/sqrt(3)};
}
if constexpr(number_of_quadrature_points == 3){
factors = {5.0/9.0, 8.0/9.0, 5.0/9.0};
points = {-sqrt(3.0/5.0), 0, sqrt(3.0/5.0)};
}
double sum = 0;
for(int i = 0; i < number_of_quadrature_points; i++){
sum += factors.at(i)*((*f)(scaling_factor*points.at(i)+average_factor));
}
sum *= scaling_factor;
return sum;
}
As you see, when the template parameter changes, not only the array size changes, but also the content is changed, but for a given size the content is well known. For this reason I think it would be better if the std::arrays were const static, as the function is called many times.
Right now I have only managed to use if constexpr to declare the array, but how can I use it both to define and declare the array so It is visible outside the if constexpr scope and the arrays are only defined once?
if constexprare great, but I would go for a specialized template in that case (for the factors/points selection).