How to pass reference-to-function into another function
26,260
#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 );
}
Author by
Hudson Worden
Updated on July 09, 2022Comments
-
Hudson Worden almost 2 years
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?
-
fredoverflow over 12 yearsJust out of curiosity, why would I want to use a reference to a function instead of a pointer to a function?
-
Cheers and hth. - Alf over 12 years@FredOverflow: Because a pointer can be null or invalid. A reference guarantees that it's valid and not null (there is no null-reference), or else that there is an error in the program.
-
newacct over 12 years@Alf P. Steinbach: "or else that there is an error in the program" That sounds great in theory but if you have something like
sometype &ref = *ptr;
the address in the pointer will be simply copied into the address in the reference, which may be non-valid or null. You might say that the statement above is undefined behavior whenptr
is non-valid or null, but there won't be any indication of this at compile- or run-time, so it is still up to the programmer to make sure it is valid and non-null, same as if you used a pointer. So I say there isn't any difference to the programmer. -
Mark Vincze almost 10 yearsI think there is a great difference. If you build up you whole codebase with using references in every API where null is not a sensible value, then the
sometype &ref = *ptr;
situation won't come up that often because you will have references everywhere. Also there is a semantical difference between accepting a reference and a pointer in an API. Accepting a reference clearly states that the function can't be called with null. If it is a reference, then it's the caller's responsibility, if it's a pointer, then it's the callee's.