Bluegreen17
Bluegreen17

Reputation: 993

Can I pass a member function of a class as a function parameter?

So I have a function in C++ which takes in another function:

double integral(double (*f)(double x){...};

I also have a class which has a member function f:

 class Test{
 public:
     double myfun(double x){...};
 };

I want to be able to call the integral function using the member function myfun of class Test. Is there a way to do this? For example, is it possible to do the following:

 Test A;
 integral(A.myfun);

I would even like to take this further and call integral within class Test, using its own member function as input!

Thanks!

Upvotes: 1

Views: 115

Answers (1)

Brian Bi
Brian Bi

Reputation: 119602

No; an ordinary function pointer cannot store the address to a non-static member function. Here are two solutions you might consider.

1) Make myfun static. Then integral(A::myfun) should compile.

2) If you have C++11 support, make the integral function take a general functor type,

template<typename Functor>
double integral(Functor f) { ... };

and bind an instance of Test to create a function object that only takes a double as an argument,

Test A;
integral(std::bind(&Test::myfun, A, std::placeholders::_1));

or simply pass a lambda,

Test A;
integral([&A](double x){ return A.myfun(x); });

Upvotes: 2

Related Questions