繁体   English   中英

将非静态成员 function 传递给另一个 class 的成员 function

[英]Pass non-static member function to member function of another class

I have two classes A and B. And I want to call the member function of class B from class A while passing a member function of A to said function of B. The setting:

class B {
    public:
        int dopristep(std::function<int(int,int)> f, double t, double h);
    };

class A {
public:
    
    void run();
    int g(int,int);
    B* mB;
};

void A::run() {

    ires         = mB->dopristep(&g,  T, h)   
}

int A::g(int,int){
//do something
}

我尝试了std::bindstd::function定义。 但它不起作用,因为它需要一个 static 成员 function 不知何故。 (我知道这里有类似的问题。但几乎所有这些问题都存在于主类中或仅在一个类中)我能找到的最相似的案例没有帮助是here

任何人都可以帮我解决这个问题吗?

ERROR:reference to non-static member function must be called

如此所述,传递一个 lambda 调用封闭A实例上的 function:

mB->dopristep([&] (int a, int b) { return g(a, b); }, T, h);

此外,您可以修改dopristep以接受一个函数,这将避免一些开销:

template <typename F>
int dopristep(F&& f, double t, double h);

暂无
暂无

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

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