linjunhalida
linjunhalida

Reputation: 4655

how to pass a member function as a function pointer?

I want add a logger function to a worker class, how to pass a member function as a function pointer? use mem_fun?

here is the code sample:

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 don't want to use void (P::*xxx)() because it stick to class P...

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

and the real project is like this:

I create a CDialog, and there is a log function, it copy the log string to a CEdit.

So I need pass this log function to a Worker class, this class do some serial port job,

I need log and show the data send and recived...

Upvotes: 4

Views: 2656

Answers (3)

James McNellis
James McNellis

Reputation: 355297

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 implementation's standard library yet; you can also get them from the Boost libraries.

Upvotes: 5

zneak
zneak

Reputation: 138251

This would require closures, that C++ doesn't exactly have. You can make functors and use templates, but you'll have to go somewhat out of your way.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308520

The only way to do it is as a static function. Unfortunately a static function isn't tied to a single object, but is global to the class. If you're lucky, the function taking a function pointer will also take a void*, which you can use to tie back to the original object - your static function can cast that back to an object pointer and call another function on the object to do the actual work.

Upvotes: 1

Related Questions