如何在子类中使用函数指针向量,并在C ++中使用父类的类型定义函数指针类型?

问题描述

有四个班级。
基本,派生1,派生2,BaseUser。
Derived1和Derived2继承基类。
最终目的是通过Base类中的虚函数在BaseUser代码上使用Derived1和Derived2函数。 (我正在实现api服务器,我想根据特定条件设置不同的api函数。)

//base_user.h
BaseUser::SetBase(Base* base);
    
//other cc file
BaseUser user;
Derived1 dev1;
Derived2 dev2;
condition ? user.SetBase(&dev1) : user.SetBase(&dev2);

顺便说一下,base.cc源代码上有一个类型定义的功能指针
(对我来说,类型定义是在类中还是在类外部都没有关系。)
从现在开始,我将类型称为 func_ptr

public: 
    typedef int(*func_ptr)(int v1,int v2,int v3);

还基类具有一个作为成员类型的向量。

protected:
    std::vector<std::pair<int,func_ptr>> functions;

我想通过将派生函数插入向量functions中来使用派生函数

如果我定义

int func1(int v1,int v3);

在任何派生类别中, 并尝试

functions.push_back(std::pair<int,func_ptr>(1,&Derived::func1));

显示一条消息,指出参数类型彼此不同。如下面的

no instance of constructor "int,func_ptr" matches -- argument type int (Derived::*)(int v1,int v3)

我认为仅在std :: pair上这不是问题。似乎func_ptr和func1的类型互不相同,因为函数func1是在Derived类中定义的。

我该如何实施?

虚拟代码(未经测试)

//Base.h
class Base{
  public:
  typedef int(*func_ptr)(int v1,int v3);
  //...//
  
  protected:
  std::vector<std::pair<int,func_ptr>> functions;
  virtual void InitializefunctionPointers();
}

//Derived1.h
class Derived1{
  int func1(int v1,int v3);
  int func2(int v1,int v3);
  void InitializefunctionPointers() override;
  //...//

  public:
  Derived1();
}

//Derived1.cc
//...//
void Derived1::InitializefunctionPointers(){
  functions.push_back(std::pair<int,&Derived1::func1));
  //...//
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)