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

C++ 指向模板类的成员函数的函数指针?(C+;+;),c++,function,pointers,member,C++,Function,Pointers,Member,我在一项作业中一直在与这个问题进行激烈的争论,但似乎根本无法让它发挥作用。我写了一个小测试类来演示我正在尝试做什么,希望有人能解释我需要做什么 //Tester class #include <iostream> using namespace std; template <typename T> class Tester { typedef void (Tester<T>::*FcnPtr)(T); private: T data;

我在一项作业中一直在与这个问题进行激烈的争论,但似乎根本无法让它发挥作用。我写了一个小测试类来演示我正在尝试做什么,希望有人能解释我需要做什么

//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;
}
//测试仪类
#包括
使用名称空间std;
模板
类测试员
{
类型定义无效(测试仪::*FcnPtr)(T);
私人:
T数据;
无效显示三次(T);
无效doFcn(FcnPtr fcn);
公众:
测试仪(T项=3);
空函数();
};
模板
内联测试仪::测试仪(T项)
:数据(项目)
{}
模板
在线空隙测试仪::doFcn(FcnPtr fcn)
{
//fcn应该是指向displayThrice的指针,然后用类数据调用displayThrice
fcn(此->数据);
}
模板
内联void测试仪::函数()
{
//使用指向displayThrice()的函数指针调用doFcn
此->doFcn(&测试仪::显示三次);
}
模板
在线无效测试仪::显示三次(T项)
{

cout您没有正确调用成员函数指针;它需要使用名为的特殊运算符

模板
在线空隙测试仪::doFcn(FcnPtr fcn)
{
(此->*fcn)(此->数据);
//   ^^^
}

要通过指向成员函数的指针和实例指针调用成员函数,需要使用
->*
语法,注意运算符优先级:

(this->*fcn)(data);

您需要显式添加要发送消息的对象:

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

(*此。*fcn)(此->数据)//如果合适的话,一定要添加家庭作业标记。另外,请看一下
boost::bind
,特别是
boost::mem\u fn
。它很有效!非常感谢。试图弄明白这一切是一场充满丑陋语法的噩梦。嗨,伙计们,尝试这段代码会给我带来两个奇怪的错误,在OS X和NetBeans中,一个未定义的符号架构x86_64:“Tester::function()”,引用自:_mainin main.o“Tester::Tester(int)”,引用自:_mainin main.o ld:未找到架构x86_64的符号clang:错误:链接器命令失败,退出代码为1(使用-v查看调用),有什么想法吗?
template <typename T>
inline void Tester<T>::doFcn( FcnPtr fcn )
{
    (this->*fcn)( this->data );
    //   ^^^
}
(this->*fcn)(data);
(*this.*fcn)(this->data); // << '*this' in this case