1

I am trying to create a somewhat general single-variable integration routine in c++. I wrote an adaptive quadrature that accepts a pointer to a single variable function, as follows:

typedef complex<double> cd;
cd GaussIntegrate(cd (*f) (cd),cd zmin,cd zmax);

However, I would like to extend it to a general multivariate function. The integration would still be on a single variable, but I would like to allow the function to depend on more than one variable, something like

cd GaussIntegrate(cd (*f) (cd, ...),cd zmin,cd zmax);

so I can use func(cd) or func(cd,double,int) as integration function, for instance.

However, I do not know what would be the best way to create such a template. There should be a way to specify the rest of the parameters, so instead of

GaussIntegrate(&function,zmin,zmax);

I should also be able to write something like

GaussIntegrate(&function(param2,param3),zmin,zmax);

Right now I am doing this through a bridge one-variable function and I specify the rest of the parameters as globals, but that is a very unelegant solution. Anyone could give me a better one?

Thanks,

Jan

legrojan
  • 569
  • 1
  • 9
  • 25

1 Answers1

2

You could use a variadic template:

typedef complex<double> cd;

template <typename... Args>
cd GaussIntegrate(cd (*f) (cd, Args...),cd zmin,cd zmax, Args... args)
{
    //Call your function like this:
    f(zmin, std::forward<Args>(args)...);

    //Do other things as needed...

    return 0;
}

Then you can call your function like this:

GaussIntegrate(f,zmin,zmax, param2, param3); //Where param2 and param3 will be forwarded to your function f

param2 and param3 can be of any type as long as they match what f is expecting.

  • 1
    You could (should) use [perfect forwarding](http://stackoverflow.com/questions/3582001/advantages-of-using-forward) – Manu343726 Oct 17 '13 at 15:53
  • Exactly what I needed. I knew someone out there had the sufficient knowledge on templates. Thank you very much! – legrojan Oct 17 '13 at 15:55
  • @Manu343726 I added forwarding to my answer. That should do it, right? –  Oct 17 '13 at 15:58
  • Just as a side note, this code does not work on VS 2012. Still not C+11 compliant enough. Let's stick to g++. – legrojan Oct 17 '13 at 16:03
  • @legrojan Yes, unfortunately VC++ is a little bit behind with C++11 features but they should have everything ready soon. –  Oct 17 '13 at 16:06
  • @KevinCadieux, I think you left out zmax as a fixed parameter in the call f(). I did get the point though. – legrojan Oct 17 '13 at 17:12