2

I was reading about delegation and I wanted to able to call within a base class any function pass as parameter depending on the event, so if for example I had a parser object and I want to assign what method from another object to call depending of what token is found. I did as bellow, it works but I am not sure if it's the proper way or if it's portable like too.

class base{
 public: 
     typedef void (base::*methodPTR)();
     methodPTR pfn;

    void setMethod(methodPTR fn)
    {
        pfn = fn;
    }
    void run(){
        if(pfn) (this->*pfn)();
    }
};

class a : public base {
 public:
};

class b : public base
{
    a ob;
 public:
     void init()
     {
             //this function fn is not define neither in object "a" or "base"
             //but still I can assign arbitrary member function just like I wanted
         ob.setMethod(static_cast<base::methodPTR>(&b::fn));
     }

     void fn()
     {
         cout << "from class b!" << endl;
     }

     void test()
     {
         ob.run();
     }
};

int _tmain(int argc, _TCHAR* argv[])
{
    b x;
    x.init();
    x.test();

    return 0;
}
7
  • 1
    The problem I see is that when you call through pfn and enter b::fn() the "this" pointer will not be correct. If you try to access a member of "b" it will get the wrong value.I added from output statements around and when b::fn() is called through the pointer "this" is pointing at the "ob" instance. This is just a side effect of "this" not really being passed and it was called from a method in the "a" class. Dec 3, 2013 at 19:32
  • @BrianWalker THX for spotting this, I've completely overseen this point (class a is used as member), which makes my answer useless. In short: Portable yes, proper way no! Dec 3, 2013 at 19:40
  • This is a fairly common way to implement polymorphism without the overhead of a vtable. Safe/portable, yes ... but you will definitely want to comment what you are doing and why (specifically explaining why you need to avoid using a vtable). Also, there is no need for the this when you are calling the function. Just call it as (*fpn)(); Dec 3, 2013 at 20:00
  • @ZacHowland 'This is a fairly common way to implement polymorphism without the overhead of a vtable' CRTP is the better choice then, IMHO. Calling a function on a different type as 'self' is surely not a 'proper' way. Dec 3, 2013 at 20:02
  • I am assuming you said is not proper because of kind of function pointer that may be pass as parameter right?
    – Jman
    Dec 3, 2013 at 20:03

2 Answers 2

0

Doing what you're doing is safe as long as you are sure that you never invoke the member pointer on an object that's not really one of the types that the pointer came from (i.e. that you don't call a a::x on a base).

2
  • I think it is a nice way to make callback functions in C++, since there is no way with the flexibility to specifying my own method and been able to use multiple callback methods. For example in LUA, you have to pass regular C function but if they would make it like this I would be able to use C++ methods, I just thought it wasn't proper or portable because I've never seen anybody using it before.
    – Jman
    Apr 7, 2014 at 16:06
  • it is as you said you don't have access to the this of pointer as they are different, so it is necessary to pass the class pointer too and call it that class pointer instead of the this o.class base{ public: typedef void (base::*methodPTR)(); typedef struct callable_fun{ base *base; methodPTR fn; }; callable_fun pfn; void setMethod(methodPTR fn, base *clase) { pfn.fn = fn; pfn.base = clase; } void run(){ if(pfn.fn) ((pfn.base)->*pfn.fn)(); } };
    – Jman
    Apr 7, 2014 at 19:58
0

Try the template solution for this problem, in this example I am sure of using right objects to invoke right functions. We could use this in case where we have a map objects and callbacks and may be call them based on some conditions.

   //store objects vs callbacks
   //you could replace int in map with some condition or key to invoke a callback
#include <iostream>
#include <map>

using namespace std;

template<class T>
class A {
  protected:
  void (T::*curr_f)();
  private:
  static std::map<int, std::map<T*,void (T::*)() > > callBacks;
  public:

  virtual void set(void (T::*f)()) {
    curr_f = f;
    cout<<"Set in A"<<endl;
    T* obj = new T();
    static int x = 0;
    callBacks[++x][obj] = f;
    //      (obj->*curr_f)();
  }

  virtual void new_function() {cout<<"in A"<<endl;};

  static void run()
  {
    for(typename std::map<int,std::map<T*,void (T::*)() > >::iterator itr = A<T>::callBacks.begin();
        itr != A<T>::callBacks.end(); ++itr)
    {
      for(typename std::map<T*,void (T::*)() >::iterator itr2 = itr->second.begin();
          itr2 != itr->second.end(); ++itr2)
      {
        ((itr2->first)->*(itr2->second))();
      }
    }
  }

};

template<class T>
std::map<int, std::map<T*,void (T::*)() > > A<T>::callBacks;

class B :public A<B> {

  public:
    void func() {
      set(&B::new_function);
    };
    void new_function() {cout<<"in B"<<endl;};

};

class C:public A<C> {

  public:
    void func() {
      set(&C::new_function);
    };
    void new_function() {cout<<"in C"<<endl;};

};

int main()
{

  B obj1;
  C obj2;
  obj1.func();
  obj2.func();
  A<B>::run();
  A<C>::run();
}
1
  • I wanted to be able call function that not necessarily were inhered, I seeing that happening in languages like Delphi where I may have a form object with some instances of buttons and when the button is trigger it calls any function member specify in the form. I seen many cases where that could be useful including cases where I wanted to write some algorithm requires callbacks or like a parser that may have some callbacks, in the case of Lua that one is limited to use C callback function.
    – Jman
    Dec 3, 2013 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.