Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass reference-to-function into another function

I have been reading about function pointers and about using them as parameters for other functions.

My question is how would you pass a function by reference without using pointers? I have been trying to find the answer on the Internet but I haven't found a good answer.

I know that you can pass variables by reference like this: void funct(int& anInt);. How would you do something similar to this, but instead of a reference to a variable, a reference to a function was the parameter?

Also, how would you use a reference to the function in a function body?

like image 561
Hudson Worden Avatar asked Aug 22 '11 03:08

Hudson Worden


People also ask

How do you pass one function to another function?

functions are first-class objects in python. you can pass them around, include them in dicts, lists, etc. Just don't include the parenthesis after the function name. Example, for a function named myfunction : myfunction means the function itself, myfunction() means to call the function and get its return value instead.

How do you pass references to a function?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

Can we pass a function to another function in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.


1 Answers

#include <iostream>
using namespace std;

void doCall( void (&f)(int) )
{
    f( 42 );
}

void foo( int x )
{
    cout << "The answer might be " << x << "." << endl;
}

int main()
{
    doCall( foo );
}
like image 112
Cheers and hth. - Alf Avatar answered Oct 03 '22 20:10

Cheers and hth. - Alf