views:

179

answers:

1

In Numerical Recipes they use something I've never seen done before, and couldn't easily find info on:

void fun( std::vector<double> derivatives(const double, const std::vector<double> &) ) { ...; derivatives(...); ...; }

Which I'm guessing is passing the function by reference (is this correct)? Why would this be favorable to using a function pointer? In which situation is each method prefered?

I have a second issue: When I invoke the function for the first time the program hangs for several seconds. Now, the argument function I pass in, itself, invokes a different function from a function pointer i.e.

  vector<double>(*pfI)(const double) = NULL;  
  ...
  pfI = pointedToFun;
  void argFun() { ...; deRefPointedFun = (*Theta::pfI)(t); deRefPointedFun(); }

What's the better way to handle 2 levels of referenced/pointer functions?

+7  A: 

This is equivalent to

void fun( std::vector (*derivatives)(const double, const std::vector &) ) { 
  ...; derivatives(...); ...; 
}

And similar to how

void f(int derivatives[]) { ... }

is equivalent to the following

void f(int *derivatives) { ... }

So the parameter is a function pointer. Functions as parameters are function pointers. And arrays as parameters are pointer to their element type. It is not similar to

void fun( std::vector (&derivatives)(const double, const std::vector &) ) { 
  ...; derivatives(...); ...; 
}

Which is a reference to a function, but only rarely used: It cannot be used for function pointer arguments, while a function pointer parameter can be used for function, function references and function pointer arguments.

Johannes Schaub - litb
As addition: Syntax in question looks more clear then using *-syntax. I think that's the reason why they used it.
Kirill V. Lyadvinsky
Alright - that makes more sense. Do you have any idea why the program hangs before the call of the first pointed to function (I've done a trace and it's definitely waiting exactly at that call)?
bias
I don't think thats problem with pointers to functions. You should post here minimal code that shows the problem so we could help you.
Kirill V. Lyadvinsky
I think I'll grab some more info and open a new thread on the second question. Thanks!
bias