简体   繁体   English

C ++将函数的参数传递给另一个函数

[英]C++ passing function in argument to another function

I am trying to pass function to a function, declaration looks like 我正在尝试将函数传递给函数,声明看起来像

double fun1(const double* ang, std::function<double(double)> f1)

In the main() , I am creating function pointer and pointing it to another function as main() ,我正在创建函数指针并将其指向另一个函数,如下所示:

std::function<double(double)> f2 = &fun5; //line1

and calling function fun1 as 并调用fun1作为

double x = fun1(&a,f2);

This works. 这可行。 But, if I call function as 但是,如果我将函数称为

double x = fun1(&a,&f2);

,it gives error as ,它给出错误为

could not convert '& f2' from 'std::function*' to 'std::function 无法将'&f2'从'std :: function *'转换为'std :: function

Creating reference works at line1 but calling function with reference does not work. 创建参考工作在line1 ,但调用函数参考不起作用。 Any idea why is this happening? 知道为什么会这样吗?

  • fun5 is a function fun5是一个函数
  • &fun5 is a pointer to a function of the type: double (*)(double) &fun5是指向以下类型的函数的指针: double (*)(double)
  • f2 is a functor object specifically of the type: function<double(double)> f2是一个函子对象,具体类型为: function<double(double)>
  • &f2 is the address of this functor object it has the type: function<double(double)>* &f2是此函子对象的地址,其类型为: function<double(double)>*

Because fun1 expects a functor object passing it a pointer to the functor object is illegal. 因为fun1期望函子对象向其传递指向该函子对象的指针是非法的。 Think about this in terms of int s if that's simpler. 如果更简单,请以int形式考虑。 If for example I have a function: void foo(int arg) , and I have an int bar I cannot do: 例如,如果我有一个函数: void foo(int arg) ,而我有一个int bar ,则无法执行以下操作:

 
 
 
  
  foo(&bar)
 
  

This whould simply be passing an int* as arg , which is obviously illegal. 该用户只是将int*作为arg传递,这显然是非法的。 What would have to happen is: 将要发生的是:

foo(bar)

Similarly your function wants a functor object. 同样,您的函数需要一个仿函数对象。 You need to pass it the functor object not the pointer, so: 您需要向它传递functor对象而不是指针,因此:

fun1(&a, f2)

首先让我们了解情况,首先您创建了f2,它是&fun5,所以基本上您已经创建了fun5的别名,它是f2,现在根据您的函数参数,第二个参数需要一个函数f2,您在第一种情况下已通过但是在第二种情况下,您需要有一个称为指针的特殊变量,以指向您已传递的引用/地址,因此将第二个参数修改为* something,第二种情况就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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