将非静态成员函数作为参数传递给另一个类中的成员函数

问题描述 投票:-3回答:2

更新我意识到这个问题缺乏适当的MCVE,我需要一些时间来提出一个问题。当我有时间回到这里时,我会更新它,抱歉。到目前为止,我很感谢答案。


关注this answer regarding static functions

宣言(在MyClass

void MyClass::func ( void (MyOtherClass::*f)(int) ); //Use of undeclared identifier 'MyOtherClass'

传递给func的函数示例:

void MyOtherClass::print ( int x ) {
      printf("%d\n", x);
}

函数调用(在MyOtherClass中)

void MyOtherClass::loop(){
    func(&MyOtherClass::print);
}

如何将成员函数作为另一个类的成员函数的参数传递?

c++ function pointers syntax
2个回答
0
投票

根据ISO,答案是"don't".与普通函数不同,如果没有类的实例,非静态成员函数就没有意义。作为一种解决方法,你可以让你的调用函数接受一个std::function并传递一个lambda。

例:

void calling_func(std::function<void()> f);

struct foo
{
    void func();

    void call()
    {
        calling_func([this]{
            func();
        });
    }
};

0
投票

难道你不能只使用std::functionstd::bind吗?

class MyOtherClass
{
public:
  MyOtherClass() {}
  void print(int x)
  {
    printf("%d\n", x);
  }
};


class MyClass
{
private:
  std::function<void()> CallbackFunc;

public:
  MyClass() {};
  void AssignFunction(std::function<void(int)> callback, int val)
  {
    CallbackFunc = std::bind(callback, val); //bind it again so that callback function gets the integer.
  }

  void DoCallback()
  {
    CallbackFunc(); //we can then just call the callback .this will, call myOtherClass::print(4)
  }
};

int main()
{
  MyClass myObject;
  MyOtherClass myOtherObject;
  int printval = 4;

  //assign the myObject.callbackfunc with the myOtherClass::print()
  myObject.AssignFunction(std::bind(&MyOtherClass::print, myOtherObject,std::placeholders::_1), 4);

  //calling the doCallback. which calls the assigned function.
  myObject.DoCallback();
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.