[英]template function taking argument function pointer to a class method
我有一个简单的课程,如下所述。
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 -
想法/代码/原因?
此致,Farrukh Arshad。
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
。 什么情况下的A
做你想做myfunction
调用func
吗? 如果是调用方的对象a
,则myfunction
需要另一个参数来提供a
,或者使用Alex所说的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
}
};
使用std::bind
;
using namespace std::placeholders;
b.myfunction(std::bind(&A::run, a, _1), mytype);
定义B如下
class B {
.
template<typename Callable, typename Arg>
void myfunction (Callable fn, Arg a) {fn(a); }
我不确定我是否很好地理解了您的问题,但是您可能想尝试使用std::function
和std::bind
,例如:
#include <functional>
#include <iostream>
struct A
{
void run(int n)
{
std::cout << "A::run(" << n << ")" << std::endl;
}
};
struct B
{
typedef std::function< void( int ) > function_type;
void driver(function_type f, int value)
{
std::cout << "B::driver() is calling:" << std::endl;
f( value );
}
};
int main()
{
A a;
B b;
b.driver(
std::bind<void>(&A::run, &a, std::placeholders::_1),
10
);
}
输出:
B :: driver()正在呼叫:
A ::运行(10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.