Image

Imagesea_gaagii wrote in Imagecpp

Derived class callback from base without templates

I know there is no error checking, I made this brief to try to illustrate my point.
(I hope I got all the non HTML chars correctly)


base.h:
#include <map>

class Base
{
  public:
    typedef void (*FN_DISPATCH)(int parm);
    void DoCall(int which, int val) {
      CallDown(dispatchTable_[which], val);
    }
  protected:
    virtual void CallDown(FN_DISPATCH, int) = 0;
    void AddDispatch(int which, FN_DISPATCH pfn) { dispatchTable_[which] = pfn; }
  private:
    std::map<int, FN_DISPATCH> dispatchTable_;
};

test.cpp:
#include "base.h"

class Derived : public Base
{
  public:
    Derived() {
      AddDispatch(1, DoOne);
      AddDispatch(2, DoTwo);
    }

    void DoOne(int val) { printf("One: %d\n", val); }
    void DoTwo(int val) { printf("Two: %d\n", val); }
    void CallDown(FN_DISPATCH fn, int val) { (this->*(fn))(val); }

};

int main(void)
{
  Derived d;
  d.DoCall(1, 5);
  d.DoCall(2, 6);

  return 0;
}

This will not compile. So the question is, how do I properly call AddDispatch and how do I form Derived::CallDown?

Thanks