How to pass a member function as a parameter to a function that does not expect this?

Let's say I have a function foo:

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

It needs parameter a void, which takes int as a parameter. Consider

void func1(int x) {}

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

Okay now foo(&func1).

But itโ€™s foo(&X::func2)not normal, because it is X::func2not static and needs a context object, and its type function pointer is different.

I tried foo(std::bind(&X:func2, this))from within X, but this also causes type mismatch.

What is the right way to do this?

0
source share
1 answer

, foo, -, ... - :

struct XFunc2Wrapper {
    static X* x;

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

foo(&XFunc2Wrapper::func2), XFunc2Wrapper::x X. , - , .

, , , ( ) foo(std::function<void(int)> ).

+2

Source: https://habr.com/ru/post/1607437/


All Articles