How do you pass a function as an argument in C++?

Born2bwire

Diamond Member
Oct 28, 2005
9,840
6
71
I have a code that needs to perform numeric integration on a variety of different integrands. Instead of doing a cumbersome hard coding using flags, I want to be able to pass as an argument a function for it to integrate. My current code compiles and works fine for the Intel C++ compiler and last I checked Visual C++ 6.0 compiler. However, I need to debug some changes and I need to compile it in Gcc and I cannot figure out the syntax. The error is typically:

Stupid preview isn't working so I can't tell how legible all of this looks.

GenLayeredGreens.cpp:3056: error: no matching function for call to ?GenLayeredGreens::Qagsint(<unresolved overloaded function type>, double&, double&, double&, double&, Dcmplx&, double&, int&, int&, int&)
GenLayeredGreens.h:73: note: candidates are: void GenLayeredGreens::Qagsint(Dcmplx (GenLayeredGreens::*)(FunctionValues*, Dcmplx), Dcmplx, Dcmplx, double, double, Dcmplx&, double&, int&, int&, int&)

The line in question is:

Qagsint(GenLayeredGreens::QuasiCorrect, za, values->r[2], eps, eps, gtm1, error, numintervals, ier, last);

The declaration of Qagsint is:

void GenLayeredGreens::Qagsint(Dcmplx(GenLayeredGreens::*f)(FunctionValues*, Dcmplx),
Dcmplx a, Dcmplx b, double epsabs, double epsrel, Dcmplx& result,
double& abserr, int& neval, int& ier, int& last)

So all of these are in the class GenLayeredGreens.



EDIT: Lord I hate fusetalk.
 

Born2bwire

Diamond Member
Oct 28, 2005
9,840
6
71
Hell I think I may have it, on the calls I need to append the function with &, like

Qagsint(&GenLayeredGreens::QuasiCorrect, za, values->r[2], eps, eps, gtm1, error, numintervals, ier, last);
 
Sep 29, 2004
18,656
68
91
The arguemnt is void*

So it is :

Foo:method(void* function)

I forget the rest .... it's been 6 years since I've had to do this.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Function pointer declarations look like this:

return_type (*pointer_name)( argument list );

So, for a function that looks like this:
int foo_function( int * p_a, double b, char c );

... you can declare a pointer to it like this:
int (*p_foo)(int*, double, char);

... and its type is:
int (*)(int*,double,char);

For completeness of reference:
Calling a function via a pointer, p_foo:
int x;
double y;
char z;
int ret = (p_foo)(&x, y, z);

The syntax is quite lame.

And of course, since functions are usually passed as pointers, you must often use the address-of operator (as you already discovered) when passing functions around.

 

Net

Golden Member
Aug 30, 2003
1,592
3
81
in your function_b parameter, pass in a pointer to function_a
 

Net

Golden Member
Aug 30, 2003
1,592
3
81
did you get it working?

here is some code:

void passThisFunc(void){

}

void accepted(void (* myFunc)(void)){

}

int main(){

accepted(passThisFunc);

return 0;
}