简体   繁体   中英

What is going on with 'function pointer' or 'reference to function' as argument to function in C++?

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 ie

  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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM