具有成员的基类需要专门用于派生类

时间:2013-05-28 09:52:34

标签: c++ templates derived-class member-function-pointers

我有一个管理方法指针的类:

template<class C>
class Prioritizer {
  public:
  typedef int (C::*FNMETHOD) ( );
  typedef std::map<unsigned int, std::vector<FNMETHOD> > methlist;

  // associate priority values with methods
  virtual void setPrio(unsigned int iPrio, FNMETHOD f);

  // call all methods for given priority
  virtual void execPrio(C *pC, int iPrio);
}

方法execPrio()需要一个指向方法指针所属的类的指针 为了调用这个方法

FNMETHOD f = ...;
(pC->*f)();

现在我有一个拥有这样一个Prioritizer对象的基类。但是这个对象只能专门用于派生类(否则我只能使用基类的方法)。 最后,我希望能够有一个从Base派生的类的集合(例如vector),并调用由其Prioritizer对象组织的方法。

我想出的最好的是:

template<class C>
class Base {
  public:
    // ... other stuff ...
    Prioritizer<C> m_prio;
}

class Der1 : public Base<Der1> {
   public:
     virtual int testDer1();
     int init() {
       m_prio->setPrio(7, testDer1);
     }; 
}

对我来说,专门化一个模板并且第一类将要定义...

似乎很尴尬

有更好的方法吗?

谢谢   乔迪

1 个答案:

答案 0 :(得分:1)

您可以在地图中存储std::function<int(void)>对象或它的升压模拟。并将任何具体的metod绑定到此函数对象时将其传递给setPrio函数。

相关问题