将方法作为参数发送到另一个类

Send method as a parameter to another class

本文关键字:另一个 参数 方法      更新时间:2023-10-16

我真的不知道如何搜索,所以我要在这里问这个问题。我知道如何将函数作为参数传递,但这次的情况有点不同,我有点不知所措。

出于可读性的原因,我将简化这些类,但如果我遗漏了一些使其混乱的内容,请告诉我。

我有一个类在另一个类中调用一个函数:

class Class1 : public ofBaseApp {
public:
    void setup() {
        class2.bindMethod(&Class1::thatFunction);
    }
    void thatFunction(Signature signature) {}
    Class2 class2;
}

然后第2类:

#include "js_delegate.h"
class Class2 {
public:
    void bindMethod(void (ofBaseApp::*func)(Signature signature)) {
        JSDelegate(this, func);
    } 
}

以及JSDelegate的定义:

template < class X, class Y >
FastDelegate2(Y *pthis, DesiredRetType (X::* function_to_bind)(Param1 p1) ) {
    m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }

如果我想这样做,我在Class1中得到一个错误,说ofApp::*ofBaseApp::*不兼容。

我想使bindMethod通用,这样我就可以传递从BaseApp继承的每个类的函数。这可以用当前的配置来完成吗?或者你可以建议另一种方法来解决这个问题吗?

干杯

因此根据注释:

template <class class_type,class function_type>
void bind_base_method(function_type function, base& instance) {
    static_assert(std::is_base_of<base,class_type>::value || std::is_same<base,class_type>::value, "class_type is not derived of base or base");
    static_assert(std::is_member_function_pointer<function_type>::value, "Function is not a member function");
}

应该根据需要为您工作。有关如何使用,请参阅此处或使用下面的示例代码:

#include <functional>
#include <type_traits>
#include <iostream> //just form cout for demonstration
class base {
    int number = 42;
public:
    void a_method(void) {
        std::cout << number << std::endl;
    }
};
class derived : public base {
};
class another_class{
public:
    void a_method(void) {
        std::cout << 41;
    }
};
template <class class_type,class function_type>
void bind_base_method(function_type function, base& instance) {
    static_assert(std::is_base_of<base,class_type>::value || std::is_same<base,class_type>::value, "class_type is not derived of base or base");
    static_assert(std::is_member_function_pointer<function_type>::value, "Function is not a member function");
    //call like
    auto this_will_call_the_method = std::bind(function, instance);
    this_will_call_the_method();
}
int main(void)
{
    derived foo;
    bind_base_method<derived>(&derived::a_method, foo);
    another_class bar;
    //bind_base_method(&another_class::a_method, bar);//error won't work as wanted
    return 0;
}