Search code examples
c++root-framework

Is there a way to create an array of functions inside a loop in C++


I'm using ROOT Cern to solve a multi-variable non-linear system of equations. For some problems I have 4 functions and 4 variables. However, for others I need 20 functions with 20 variables. I'm using a class called "WrappedParamFunction" to wrap the functions and then I add the wrapped functions to the "GSLMultiRootFinder" to solve them. The function is wrapped this way:

ROOT::Math::WrappedParamFunction<> g0(&f0, "number of variables", "number of parameters");

Therefore, I need to declare the f0...fi functions before my void main(){} part of the code. I'm declaring the functions in this way:

double f0(const double *x, const double *par){return -par[0]+y[0]*par[1];}
double f1(const double *x, const double *par){return -par[1]+y[1]*par[2];}
.
.

Is there a way to create those functions inside a loop and stack them in an array? Something like this:

double (*f[20])(const double *x, const double *par);
for(int i=0;i<20;i++){
   f[i]= -par[i]+x[i]*par[i+1];
}

So that later I can wrap the functions in this way:

ROOT::Math::WrappedParamFunction<> g0(f[0], "number of variables", "number of parameters");

Solution

  • Making your i a template parameter and generating the functions recursively at compile time can also do the trick:

    using FunctionPrototype = double(*)(const double *, const double *);
    
    template<int i>
    double func(const double * x, const double * par) {
      return -par[i]+x[i]*par[i+1];
    }
    
    template<int i>
    void generate_rec(FunctionPrototype f[]) {
      f[i-1] = &func<i-1>;
      generate_rec<i-1>(f);
    }
    
    template<>
    void generate_rec<0>(FunctionPrototype f[]) { }
    
    template<int i>
    FunctionPrototype* generate_functions()
    {
      FunctionPrototype * f = new FunctionPrototype[i]();
      generate_rec<i>(f);
      return f;
    }
    
    
    FunctionPrototype * myFuncs = generate_functions<3>(); // myFuncs is now an array of 3 functions