如何将成员函数作为参数传递给不期望它的函数? [英] How to pass a member function as a parameter to a function that doesn't expect it?

查看:72
本文介绍了如何将成员函数作为参数传递给不期望它的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个函数foo:

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

它需要一个void函数作为参数,该函数接受一个int作为参数.考虑

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) {}
};

现在 foo(&func1)可以.

但是foo(&X::func2)并不正确,因为X::func2不是静态的并且需要上下文对象,并且其功能指针 type 是不同的.

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.

我从X内部尝试了foo(std::bind(&X:func2, this)),但这也引起了类型不匹配.

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

正确的做法是什么?

推荐答案

基于注释,如果您不能将foo的签名更改为除原始函数指针之外的任何内容,那么您就必须这样做像这样的东西:

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);
    }
};

然后只要将XFunc2Wrapper::x设置为X,就执行foo(&XFunc2Wrapper::func2).它不必嵌套在结构中,它可以只是一些全局指针,但是嵌套有助于更好地建立代码背后的意图.

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.

但这绝对是(按照Obvlious上尉的)尝试执行foo(std::function<void(int)> )之后的不得已的手段.

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

这篇关于如何将成员函数作为参数传递给不期望它的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆