“函数指针”或“函数引用”作为C ++函数的参数是怎么回事?

时间:2020-12-12 21:39:59

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?

处理2级引用/指针函数的更好方法是什么?

1 个解决方案

#1


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.

这是对函数的引用,但很少使用:它不能用于函数指针参数,而函数指针参数可用于函数,函数引用和函数指针参数。

#1


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.

这是对函数的引用,但很少使用:它不能用于函数指针参数,而函数指针参数可用于函数,函数引用和函数指针参数。