简体   繁体   English

如何将成员函数作为参数传递给不期望它的函数?

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

Say I have a function foo : 说我有一个函数foo

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

It needs as a parameter a void function that accepts an int as a parameter. 它需要一个接受int作为参数的void函数作为参数。 Consider 考虑

void func1(int x) {}

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

Now foo(&func1) is ok. 现在foo(&func1)可以了。

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. 但是foo(&X::func2)因为X::func2不是静态的,并且需要上下文对象,并且其函数指针类型不同。

I tried foo(std::bind(&X:func2, this)) from inside X but that raises a type mismatch too. 我从X内部尝试了foo(std::bind(&X:func2, this)) ,但这也引发了类型不匹配的情况。

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: 根据注释,如果您不能将foo的签名更改为采用原始函数指针之外的任何形式,那么您将必须执行以下操作:

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 . 然后,一旦将XFunc2Wrapper::x设置为X就执行foo(&XFunc2Wrapper::func2) 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)> ) . 但这绝对是(按照Obvlious上尉的)尝试做foo(std::function<void(int)> )之后的不得已的手段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM