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

6

我一直在为一个作业中的这个问题苦苦挣扎,但似乎根本无法让它工作。我写了一个小的测试类来演示我所想要做的事情,希望有人能够解释我需要做什么。

//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类中的注释能够告诉您我想要做什么。感谢您抽出时间查看!


如果适用的话,请确保添加作业标签。此外,请查看boost::bind,特别是boost::mem_fn - Tom Kerr
3个回答

11

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

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

大家好,尝试运行这段代码在OS X和NetBeans中出现了2个奇怪的错误。Undefined symbols for architecture x86_64: "Tester<int>::function()", referenced from: _main in main.o "Tester<int>::Tester(int)", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)有任何想法吗? - Anders S

2
要通过指向成员函数的指针加实例指针来调用成员函数,您需要使用->*语法,并注意运算符优先级:
(this->*fcn)(data);

成功了!非常感谢。试图弄清楚所有这些都是一个充满丑陋语法的噩梦。 - TNTisCOOL

1

您需要明确添加您要发送消息的对象:

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

另请参阅C++ FAQ


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接