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

时间:2015-02-19 14:49:34

标签: c++ templates

我想使用和使用指向某个成员函数的指针,我也希望能够回调那个(或其他)成员函数。 可以说,我有这样的标题:

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(__ thistallcall)   T :: *)(void),T *)':无法推断'重载'的模板参数   函数类型'from'重载函数类型'

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

使用Microsoft Visual C ++ 6.0。我究竟做错了什么?我不能用boost。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您需要传递函数地址

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