1

How would the signature for function Foo() fo class classA have to look when I want to pass a pointer to a function that is a member of classB? Function update() is called on an isntance of classB and gets passed an object of classA. Inside update() the function Foo() of classA shall be passed a pointer to a callback function. That function is a member of classB. I can't make anything static here. Is there a way to do this, maybe with boost::function ?

Code:

class classA
{
 public:
  voif Foo(/*a pointer to a memberfunction of ClassB*/)
};

class classB
{
 classB(){nVal = 0;}
 int nVal;
 public:
 void increment(int n){nVal += n;}
 void update(classA objA)
 {
  objA.Foo(increment)
 }
};
tzippy
  • 6,458
  • 30
  • 82
  • 151
  • Use inheritance and virtual functions. That's why this mechanism is there for. – barak manos Aug 01 '14 at 11:20
  • 1
    You might want to read about [`std::function`](http://en.cppreference.com/w/cpp/utility/functional/function) and [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/bind). – Some programmer dude Aug 01 '14 at 11:21
  • @JoachimPileborg: Thank you. I wasn't aware of std::function and std::bind. – Fish Aug 01 '14 at 11:49
  • @barakmanos: In the above case, how exactly is inheritance gonna help, when types `classA` and `classB` are clearly distinct and `Foo()` in `classA` is merely taking a ref to some callable? – thokra Aug 01 '14 at 11:54

1 Answers1

4

You can use boost::bind with boost::function.

class classA
{
public:
   void Foo(const boost::function<void(int)>& function)
   {
   }
};

class classB
{
public:
   //
   void update(classA objA)
   {
       objA.Foo(boost::bind(&classB::increment, this, _1));
   }
};
ForEveR
  • 55,233
  • 2
  • 119
  • 133