Tôi đã chống đầu của tôi chống lại vấn đề này trong một nhiệm vụ tôi đã được làm việc trên, và dường như không thể làm cho nó hoạt động cả. Tôi đã viết một bài kiểm tra nhỏ để chứng minh những gì tôi đang cố gắng làm, và hy vọng ai đó có thể giải thích những gì tôi cần làm.Hàm con trỏ tới hàm thành viên của lớp mẫu? (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;
}
-Và đây là chính:
#include <iostream>
#include "Tester.h"
using namespace std;
int main()
{
Tester<int> test;
test.function();
cin.get();
return 0;
}
-Và cuối cùng, lỗi biên dịch của tôi (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> ]
Hy vọng rằng, ý kiến của tôi trong lớp Tester sẽ cho bạn biết những gì tôi m cố gắng làm. Cảm ơn bạn đã dành thời gian để xem xét điều này!
Hãy chắc chắn để thêm thẻ bài tập về nhà nếu thích hợp. Ngoài ra, hãy xem 'boost :: bind', cụ thể là 'boost :: mem_fn'. –