指向成员函数的指针,作为全局函数的参数 [英] Pointer to member function for as argument for global function

查看:139
本文介绍了指向成员函数的指针,作为全局函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的代码:

  void foo(void(* fun_ptr)()){

}

class B {
public:
B(){
foo(some_fun);
}
void some_fun(){}
};

编译错误:

 错误:类型为'void(B ::)()'的参数不匹配'void(*)()'

在这种情况下如何指向成员函数?我不能改变函数声明foo,只有类B!

解决方案

这是一个常见问题。 b
$ b

除了将成员函数包装在静态函数中以外,没有其他解决方案,而是以某种方式告诉它关于调用方法的对象实例:

  struct X {void foo(); } 

void take_callback(void(* fun_ptr)())
{
fun_ptr(); // invoke callback
}

//换方法

X * instance = 0;

void wrap_memberfun()
{
if(instance)instance-> foo(); // delegate
}

int main()
{
X x;
take_callback(& X :: foo); //不编译

//解决方法:
instance =& x;
take_callback(& wrap_memberfun);
}


There is such code:

void foo(void (*fun_ptr)()){

}

class B{
public:
    B(){
        foo(some_fun);
    }
    void some_fun(){}
};

Compilation error:

error: argument of type ‘void (B::)()’ does not match ‘void (*)()’

How to point to member function in this case? I cannot change declaration of function foo, only class B!

解决方案

This a FAQ in it's own right.

There is no other solution than to wrap the member function in a static function and somehow tell it about the object instance to invoke the method on:

struct X { void foo(); }

void take_callback(void (*fun_ptr)())
{
      fun_ptr(); // invoke callback
}

//wrap the method

X* instance = 0;

void wrap_memberfun()
{
    if (instance) instance->foo(); // delegate
}

int main()
{
      X x;
      take_callback(&X::foo); // doesn't compile

      // workaround:
      instance = &x;
      take_callback(&wrap_memberfun);
}

这篇关于指向成员函数的指针,作为全局函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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