简体   繁体   English

成员函数的模板和指针

[英]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: 和cpp像这样:

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' main.h(22):错误C2784:'void __thiscall A :: Add(bool(__thiscall T :: *)(void),T *)':无法从'overloaded function'推断'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 我需要从许多类中调用A :: Add(并发送有关类方法及其实例的信息),所以这就是我要使用模板的原因

Using Microsoft Visual C++ 6.0. 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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