函数指向模板类的成员函数?(C++)

TNT*_*OOL 5 c++ pointers function member

在我一直致力于的任务中,我一直在反对这个问题,而且似乎无法让它完全发挥作用.我写了一个小测试类来演示我正在尝试做什么,希望有人可以解释我需要做什么.

//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;
}
Run Code Online (Sandbox Code Playgroud)

- 这里是主要的:

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

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

    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

- 最后,我的编译器错误(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>          ]
Run Code Online (Sandbox Code Playgroud)

希望我在Tester课上的评论会告诉你我想要做什么.感谢您抽出宝贵时间来看看这个!

Ada*_*ras 10

你没有正确地调用成员函数指针; 它需要使用一个称为指向成员运算符的特殊运算.

template <typename T>
inline void Tester<T>::doFcn( FcnPtr fcn )
{
    (this->*fcn)( this->data );
    //   ^^^
}
Run Code Online (Sandbox Code Playgroud)