将方法作为参数发送到另一个类
Send method as a parameter to another class
我真的不知道如何搜索,所以我要在这里问这个问题。我知道如何将函数作为参数传递,但这次的情况有点不同,我有点不知所措。
出于可读性的原因,我将简化这些类,但如果我遗漏了一些使其混乱的内容,请告诉我。
我有一个类在另一个类中调用一个函数:
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;
}
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如果需要转换,我可以在读取参数的同时将其移动到另一个参数吗?
- 如何在另一个函数中使用返回值作为参数?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 如何使用另一个类中的公共成员函数作为参数调用线程
- 如何将 lambda 函数作为参数发送到另一个函数
- 如何设置默认参数以防用户不输入另一个参数
- 将另一个参数传递给函子的库
- 一个C++默认参数可以用另一个参数初始化吗
- 从另一个参数引用的模板可变参数
- 如何根据c++中getopt中另一个参数的存在来解析其他参数
- 如何让每个线程传递另一个参数
- 从另一个参数的值设置默认参数值
- 使用参数的 getter 之一在 C++ 函数中设置另一个参数的值?
- Qt:用另一个参数创建一个新类
- 谷歌模拟,使用另一个参数的参数匹配器
- 非类型模板参数,其类型依赖于另一个参数