What does it mean to pass a function name?

  • Thread starter Steven T. Hatton
  • Start date
S

Steven T. Hatton

In this example:
void print(int i) { std::cout<<i<<" "; }
for_each(coll.begin(), coll.end(), print);

What kind of entity is "print" when it appears as an actual parameter in the
for_each function call? It's not an object. Should it be thought of as a
reference to the addressable location which would be pointed to by a
function pointer? Is it an "alias" for a function pointer?
 
N

Noah Roberts

Steven said:
In this example:
void print(int i) { std::cout<<i<<" "; }
for_each(coll.begin(), coll.end(), print);

What kind of entity is "print" when it appears as an actual parameter in the
for_each function call? It's not an object. Should it be thought of as a
reference to the addressable location which would be pointed to by a
function pointer? Is it an "alias" for a function pointer?

It's a function address. You can omit the & for plain functions that
are not class members.
 
D

Daniel T.

Steven said:
In this example:
void print(int i) { std::cout<<i<<" "; }
for_each(coll.begin(), coll.end(), print);

What kind of entity is "print" when it appears as an actual
parameter in the for_each function call?

It is a pointer to a function. A pointer of type "void (*)(int)".
Should it be thought of as a reference to the addressable location
which would be pointed to by a function pointer?

Not a reference to it, but the addressable location itself.

Maybe the following code will help explain things:

void print( int i ) { cout << i << '\n'; }
void print2( int i ) { cout << ( i * i ) << '\n'; }

template < typename Func >
void call( Func f, int i )
{
f( i );
}

int main()
{
void (*func)(int) = 0;
func = print;
func( 3 );
func = print2;
func( 3 );
// the above is how virtual functions are done in C

// below shows how your function is being used in for_each
call( print, 5 );
call( print2, 5 );
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top