简体   繁体   中英

templates and pointers to member functions

I would like to use and work with pointer to some member function and I also want to be able to call that (or other) member function back. Lets say, I have headers like this:

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);
  }
};

and cpp like this:

main(){
  B f;
  f.Bfoo2();
}

I've got following error:

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'

I need to call A::Add from many classes (and send information about class method and its instance) so that's why I want to use templates

Using Microsoft Visual C++ 6.0. What am I doing wrong? I cannot use boost.

In my opinion, right way to do what you need is to use inheritance, for example:

class A {
  virtual void Add() = 0;
}

class B : public A {
  void Add() {...}
}

class C : public A {
  void Add() {...}
}

So in your main you can do:

A* a = new B();
a->Add(); /* this call B::Add() method */

您需要传递一个函数地址

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM