How to pass a member function as a function pointer?

I want to add a log function to a working class, how do I pass a member function as a function pointer? use mem_fun?

here is a sample code:

class Work{ public: void (*logger) (const string &s); void do_sth(){if (logger) logger("on log")}; }; classs P{ public: void log(const string &s)(cout << s); }; int main(){ Work w; P p; w.logger = &p.log; w.do_sth(); } 

edit:

I do not want to use void (P :: * xxx) () because it adheres to the class P ...

I know C ++ hide sth, the real log function: void log (P & p, const string & s),

and the real project is as follows:

I create a CDialog, and there is a log function, it copies the log line to CEdit.

So, I need to pass this log function to the Worker class, this class does some serial port job,

I need a log and show the data to send and receive ...

+4
source share
3 answers

You can accomplish this using std::function and std::bind :

 #include <functional> #include <iostream> #include <string> class Work { public: std::function<void(const std::string&)> logger; void do_sth() { logger("on log"); } }; class P { public: void log(const std::string& s) { std::cout << s; } }; int main() { Work w; P p; w.logger = std::bind(&P::log, p, std::placeholders::_1); w.do_sth(); } 

Note that function and bind may not be in your standard implementation library; You can also get them from the Boost libraries .

+4
source

The only way to do this is with a static function. Unfortunately, a static function is not bound to a single object, but is global to the class. If you're lucky, a function that uses a function pointer will also accept void *, which you can use to bind to the original object - your static function can drop that back to the object pointer and call another function on the object, do the actual work.

+1
source

This will require closure, which C ++ definitely does not have. You can create functors and use templates, but you have to get a little distracted.

0
source

All Articles