简体   繁体   中英

How to pass a member function as a parameter to a function that doesn't expect it?

Say I have a function foo :

void foo(void (*ftn)(int x))
{
  ftn(5);
}

It needs as a parameter a void function that accepts an int as a parameter. Consider

void func1(int x) {}

class X {
public:
  void func2(int x) {}
};

Now foo(&func1) is ok.

But foo(&X::func2) isn't ok because X::func2 isn't static and needs a context object and its function pointer type is different.

I tried foo(std::bind(&X:func2, this)) from inside X but that raises a type mismatch too.

What is the right way of doing this?

Based on the comments, if you cannot change the signature of foo to take anything but a raw function pointer... then you'll have to do something like this:

struct XFunc2Wrapper {
    static X* x;

    static void func2(int v) {
        x->func2(v);
    }
};

And then just do foo(&XFunc2Wrapper::func2) once you set XFunc2Wrapper::x to be your X . It doesn't have to be nested in a struct, it can just be some global pointer, but nesting helps establish the intent behind the code better.

But this should definitely be last resort after (as per Captain Obvlious) trying to do foo(std::function<void(int)> ) .

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