【问题标题】:Passing non-static member function as argument to a member function in a different class将非静态成员函数作为参数传递给不同类中的成员函数
【发布时间】:2019-03-14 12:20:39
【问题描述】:

更新我意识到这个问题缺少适当的 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);
}

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

【问题讨论】:

  • 使用std::function作为参数和一个lambda绑定到MyOtherClass的实例。
  • 您是否在问为什么会收到“使用未声明的标识符”错误?
  • 不清楚问题出在哪里,但是关于方法指针的一些很好的通用阅读:isocpp.org/wiki/faq/pointers-to-members
  • @DrewDormann 基本上是的!这是一个语法问题。我正在尝试将成员函数作为另一个成员函数的参数传递,但是成员函数位于不同的命名空间中,因此无法遵循各种在线教程/说明中的语法。
  • 不清楚,因为很难说出你想用它做什么。你做的大部分事情都是正确的。部分原因是我的错,我没有将屏幕滚动到足以看到评论中的错误消息。一旦我这样做了,很明显你的问题是MyOtherClassMyClass::func 之前没有被声明。编译器还没有看到MyOtherClass 并且不确定如何解释未知标识符。 minimal reproducible example 会让一切变得一清二楚。

标签: c++ function pointers syntax


【解决方案1】:

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

例子:

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

struct foo
{
    void func();

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

【讨论】:

    【解决方案2】:

    你不能只使用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;
    }
    

    【讨论】:

    • 他们可能可以,而且这将是一个更好的解决方案(虽然不如std::function 和 lambda 好),但这不是他们遇到的问题。没有 MCVE 就无法确定实际问题。
    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2019-09-27
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多