1

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!

3
  • I've never needed to and am not sure you can. I do this for static functions, but for regular member functions I arrange things to use polymorphism or function objects. Commented Feb 28, 2014 at 6:21
  • Is your integral function your own? Can you make modifications to it, to accept other types? Commented Feb 28, 2014 at 6:21
  • In this example, yes it is. But for the real problem, this function is not something I can easily change. Commented Feb 28, 2014 at 6:42

1 Answer 1

2

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); });
Sign up to request clarification or add additional context in comments.

1 Comment

You can use the boost libraries and get boost::bind if you don't have c++11 support.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.