LindaZ LindaZ - 4 months ago 21
C++ Question

A delegate implementation in C++

I have started and I don't know how to continue.

Say we have classA and classB.

classA create an instance of classB , then classB should call a method in classA :

classA .h:

#include "classB.hpp"

class classA
{
public:

classA();
classB *b ;
float someDelegate(char *arg); // a method I would like to call from B


classA .cpp: ( just part of it )

#include "classA.hpp"


classA::classA()
{

b=new classB(); // instance of B

***QUESTION IS HERE- WHAT TO PASS TO THE FUNCTION****

b>-setDelegate(???) ?


}


On classB .h I have :

class classB
{


public:

classB( );
float (*fpAction)(char*) = 0 ;


on classB.cpp :

void classB::setDelegate( float(*fp)(char*))
{
fpAction=fp; //set the pointer for the delegate

}


Well, I know this might be wrong to do, in this case I will be happy to see how you should do this correctly.

The goal still is, to let classB call classA method with some argument

Answer

One way to do it is to use std::function

class B{
  ...
  std::function<float(char*)> func;
};

class A{
  A();
  ...
  B memberClassB;

  float someDelegate(char* arg);
};
A::A(){
  memberClassB.func = std::bind(&A::someDelegate, this, _1);
}

Then, whenever func is called, it should run someDelegate from the class A that created it.