2013-01-18 55 views
2

我有一个简单的类,如下所述。模板函数将参数函数指针指向一个类方法

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 - 

想法/代码/原因?

Regards, Farrukh Arshad。

回答

2

使用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); } 
3
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 
    } 
}; 
1

我不知道我理解你的问题很好,但你可能要使用std::functionstd::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 ::驱动程序()在调用:

A ::运行(10)

相关问题