2013-01-18 53 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)

相關問題