我有一个简单的类,如下所述。
typedef mytype int;
typedef mytype2 float;
class A {
.
.
void run (mytype t) { .... do something with t ..... }
.
.
}
我有另一个类,我在其中创建了一个模板函数(使其独立于 A 类),它应该将函数指针(即 A 类方法运行)及其参数。
class B {
.
template< // how it should be defined >
void myfunction ( // how parameters will be passed ) { }
驱动应该是这样的
A a
B b
C c
b.myfunction(&A::run, mytype); // Or how it should be called
b.myfunction(&B::run, mytype2); // - do -
想法/代码/原因?
问候, 法鲁克阿尔沙德。
最佳答案
class B {
template <typename T>
void myfunction(void (T::*func)(mytype), mytype val) {
(some_instance_of_T.*func)(val); // or whatever implementation you want
}
};
参数func
被定义为指向T
的非静态成员函数的指针,取mytype
并返回void
。
您需要从某处获取some_instance_of_T
。您希望 myfunction
调用 func
的哪个 A
实例?如果它是调用者的对象 a
,那么 myfunction
需要另一个参数来提供 a
,或者使用 bind
作为亚历克斯说,并定义:
class B {
template <typename Functor>
void myfunction(Functor f, mytype val) {
f(val); // or whatever implementation you want
}
};
或者如果您想限制用户传入的内容的类型:
class B {
void myfunction(std::function<void(mytype)> f, mytype val) {
f(val); // or whatever implementation you want
}
};
关于c++ - 模板函数将参数函数指针指向类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14397733/