模板和指向成员函数的指针

templates and pointers to member functions

本文关键字:函数 指针 成员      更新时间:2023-10-16

我想使用指向某个成员函数的指针并与之一起工作,我还希望能够回调该(或其他)成员函数。比方说,我有这样的标题:

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):错误C2784:"void __thiscall A::Add(bool(__thiscaallT: :*)(void),T*)":无法推导"重载的模板参数"重载函数类型"中的"函数类型"

我需要从许多类中调用A::Add(并发送关于类方法及其实例的信息),所以这就是我想要使用模板的原因

使用Microsoft Visual C++6.0。我做错了什么?我不能使用助推。

在我看来,正确的方法是使用继承,例如:

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 */

您需要传递函数的地址

a.Add(&B::Bfoo, this);