I am writing code to perform Gaussian integration with n points, where n is a compile time constant.
For a given n, I know how to compute abscissas and weights. The computation has to be done from scratch for each different n.
Now, I do something along these lines:
// Several structs like this one (laguerre, chebyshev, etc).
template <size_t n>
struct legendre
{
static const size_t size = n;
static const double x[n];
static const double w[n];
};
template <typename Rule, typename F>
double gauss_quadrature (F&& f)
{
double acc = 0;
for (size_t j = 0; j < Rule::size; j++)
acc += Rule::w[j] * f (Rule::x[j]);
return acc;
}
to be used like this:
double i = gauss_quadrature<legendre<12>> (f);
Now, I can specialize in a translation unit the coefficients for legendre<12>, by doing
template <>
const legendre<12>::x[12] = { ... };
template <>
const legendre<12>::w[12] = { ... };
and everything is fine, as long as I only use 12-points Gauss-Legendre.
Now, I'm experimenting with different number of points, and I know how to generate the weights and nodes. I can for instance provide a routine
void compute_legendre_coeffs (size_t n, double* w, double* x);
and :
- When I call
gauss_quadrature<legendre<n>>, the templatelegendre<n>is automatically instantiated (this is the case). - When
legendre<n>is instantiated for some compile-timen, I'd like the abovecompute_legendre_coeffsto be called at some point before main so that it fills thexandwmember arrays. How do I achieve this ?
I know must define the arrays first:
template <size_t n>
const double legendre<n>::x[n] = {};
template <size_t n>
const double legendre<n>::w[n] = {};
but I can't come up with a method to initialize them. Anyone has a trick to do so ?
typedef const double (&arr_ref)[n];andstatic arr_ref get_x(){ static const double x[n] = {}; static char c = (init(x),'0'); return x; }.nand the array known at compile time.main, but just before the first use. Right? If that is the case, you can make the coefficientsprivateand offer astaticaccessor that ensures the initialization of the arrays