2011-10-17 101 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