繁体   English   中英

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

[英]Function Pointer to member function of template class? (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>          ]

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

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

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

另见C ++ FAQ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM