• Advertisement
Sign in to follow this  

[C++]Pointers to functions

This topic is 3700 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How do I create a pointer to a function, pass this pointer as an argument to another function, and execute the function my pointer points to?

Share this post


Link to post
Share on other sites
Advertisement

// for sanity, use a typedef

typedef int (*MathFunctionPtr)( int );

int half( int arg )
{
return arg / 2;
}

int twice( int arg )
{
return arg * 2;
}

void foo( MathFunctionPtr function, int arg )
{
// note: no need to dereference.
// calling it looks the same as a non-function pointer
std::cout << "calling this function on " << arg << " returns " << function(arg) << '\n';
}

int main()
{
foo(&half,10);
// note: no need to explicitly take address
foo(twice,20);
}





For stateful functions, you can use a template which takes either a function pointer or a functor (a struct/class with the appropriate operator() overload):


struct half
{
int operator()( int arg ) const
{
return arg / 2;
}
};

struct multiply_by
{
int amount;
multiply_by( int a ) : amount(a) {}
int operator()( int arg ) const
{
return amount * arg;
}
};

int thrice( int arg )
{
return arg * 3;
}

template< class MathFunctor >
void foo( MathFunctor function, int arg )
{
// note: no need to dereference.
// calling it looks the same as a non-function pointer
std::cout << "calling this function on " << arg << " returns " << function(arg) << '\n';
}

int main()
{
foo(half(),10);
foo(multiply_by(3),20);
// can pass function pointers to the template too!
foo(&thrice,6);
}





The Standard C++ Library and boost both make use of functors, while providing convenience functors in turn.

As for member function pointers, see <http://www.parashift.com/c++-faq-lite/pointers-to-members.html">The C++ FAQ (lite).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement