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

安稳与你 提交于 2019-12-13 04:58:33

问题


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?


回答1:


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)> ).



来源:https://stackoverflow.com/questions/26691656/how-to-pass-a-member-function-as-a-parameter-to-a-function-that-doesnt-expect-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!