简体   繁体   中英

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!

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); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM