2011-10-17 4 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; 
} 

- 그리고 마지막으로, 내 컴파일러 오류 (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

멤버 함수 포인터를 corrently 호출하지 않습니다. pointer-to-member operator이라는 특수 연산자를 사용해야합니다. 당신은 명시 적으로 객체를 추가 할 필요가

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

거의 정확하지만 대괄호가 없습니다. – UncleBens

+0

오우, 참으로. 고맙습니다! –

+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

관련 문제