nuninek
nuninek

Reputation: 3

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.

Upvotes: 0

Views: 88

Answers (2)

Luca Davanzo
Luca Davanzo

Reputation: 21520

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

Upvotes: 1

Nikolay K
Nikolay K

Reputation: 3850

You need to pass an address of function

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

Upvotes: 0

Related Questions