Sign in to follow this  

[C++]Pointers to functions

This topic is 3627 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


// 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

This topic is 3627 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this