2011-10-17 98 views
5

在我一直在做的任務中,我一直在反駁這個問題,並且似乎無法完全解決這個問題。我寫了一個小測試課來證明我正在做什麼,希望有人能解釋我需要做的事情。函數指向模板類成員函數的指針? (C++)

//Tester class 
#include <iostream> 
using namespace std; 

template <typename T> 
class Tester 
{ 
    typedef void (Tester<T>::*FcnPtr)(T); 

private: 
    T data; 
    void displayThrice(T); 
    void doFcn(FcnPtr fcn); 

public: 
    Tester(T item = 3); 
    void function(); 
}; 

template <typename T> 
inline Tester<T>::Tester(T item) 
    : data(item) 
{} 

template <typename T> 
inline void Tester<T>::doFcn(FcnPtr fcn) 
{ 
    //fcn should be a pointer to displayThrice, which is then called with the class data 
    fcn(this->data); 
} 

template <typename T> 
inline void Tester<T>::function() 
{ 
    //call doFcn with a function pointer to displayThrice() 
    this->doFcn(&Tester<T>::displayThrice); 
} 

template <typename T> 
inline void Tester<T>::displayThrice(T item) 
{ 
    cout << item << endl; 
    cout << item << endl; 
    cout << item << endl; 
} 

- 和這裏的主:

#include <iostream> 
#include "Tester.h" 
using namespace std; 

int main() 
{ 
    Tester<int> test; 
    test.function(); 

    cin.get(); 
    return 0; 
} 

-and最後,我的編譯器錯誤(VS2010)

c:\users\name\documents\visual studio 2010\projects\example\example\tester.h(28): error C2064: term does not evaluate to a function taking 1 arguments 
1>   c:\users\name\documents\visual studio 2010\projects\example\example\tester.h(26) : while compiling class template member function 'void Tester<T>::doFcn(void (__thiscall Tester<T>::*)(T))' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
1>   c:\users\name\documents\visual studio 2010\projects\example\example\tester.h(21) : while compiling class template member function 'Tester<T>::Tester(T)' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
1>   c:\users\name\documents\visual studio 2010\projects\example\example\example.cpp(7) : see reference to class template instantiation 'Tester<T>' being compiled 
1>   with 
1>   [ 
1>    T=int 
1>   ] 

希望,我在測試類註釋會告訴你我米試圖做。感謝您花時間看這個!

+0

確保如果合適,添加作業標籤。另外,請看'boost :: bind',特別是'boost :: mem_fn'。 –

回答

10

你沒有正確地調用成員函數指針;它需要使用一個稱爲pointer-to-member operator的特殊操作符。

(this->*fcn)(data); 
+0

幾乎正確,但缺少一對括號。 – UncleBens

+0

Oy的確如此。謝謝! –

+0

非常感謝! – TNTisCOOL

1

要通過指針到成員函數加實例指針,你需要的->*語法,自掃門前雪運算符優先級調用一個成員函數消息:

(*this.*fcn)(this->data); // << '*this' in this case 

又見C++ FAQ

+0

它的工作原理!非常感謝。試圖弄清楚所有這一切是一場充滿醜陋語法的噩夢。 – TNTisCOOL

1

你需要明確地添加你的對象:

template <typename T> 
inline void Tester<T>::doFcn(FcnPtr fcn) 
{ 
    (this->*fcn)(this->data); 
    // ^^^ 
} 
+0

它的工作原理!謝謝! – TNTisCOOL