成员函数的模板和指针
templates and pointers to member functions
我想使用和处理指向某个成员函数的指针,我还希望能够调用那个(或其他)成员函数。
比方说,我有 headers 这样的:
class A{
public:
template<class T> void Add(bool (T::*func)(), T* member){
((member)->*(func))();
}
};
class B{
public:
bool Bfoo(){return 1;}
void Bfoo2(){
A a;
a.Add(Bfoo, this);
}
};
和 cpp 这样的:
main(){
B f;
f.Bfoo2();
}
我遇到以下错误:
main.h(22) : error C2784: 'void __thiscall A::Add(bool (__thiscall
T::*)(void),T *)' : could not deduce template argument for 'overloaded
function type' from 'overloaded function type'
我需要从许多 class 中调用 A::Add(并发送有关 class 方法及其实例的信息),所以这就是我想使用模板的原因
使用 Microsoft Visual C++ 6.0。我究竟做错了什么?我无法使用 boost。
你需要传递函数的地址
a.Add(&B::Bfoo, this);
在我看来,做你需要做的事情的正确方法是使用继承,例如:
class A {
virtual void Add() = 0;
}
class B : public A {
void Add() {...}
}
class C : public A {
void Add() {...}
}
所以在你的主要任务中你可以这样做:
A* a = new B();
a->Add(); /* this call B::Add() method */
我想使用和处理指向某个成员函数的指针,我还希望能够调用那个(或其他)成员函数。 比方说,我有 headers 这样的:
class A{
public:
template<class T> void Add(bool (T::*func)(), T* member){
((member)->*(func))();
}
};
class B{
public:
bool Bfoo(){return 1;}
void Bfoo2(){
A a;
a.Add(Bfoo, this);
}
};
和 cpp 这样的:
main(){
B f;
f.Bfoo2();
}
我遇到以下错误:
main.h(22) : error C2784: 'void __thiscall A::Add(bool (__thiscall T::*)(void),T *)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type'
我需要从许多 class 中调用 A::Add(并发送有关 class 方法及其实例的信息),所以这就是我想使用模板的原因
使用 Microsoft Visual C++ 6.0。我究竟做错了什么?我无法使用 boost。
你需要传递函数的地址
a.Add(&B::Bfoo, this);
在我看来,做你需要做的事情的正确方法是使用继承,例如:
class A {
virtual void Add() = 0;
}
class B : public A {
void Add() {...}
}
class C : public A {
void Add() {...}
}
所以在你的主要任务中你可以这样做:
A* a = new B();
a->Add(); /* this call B::Add() method */