lundi 7 septembre 2020

C++ Call an abstract class method using member function pointer

I have an abstract class:

class Proto{
public:
  virtual void fu() = 0;
};

Then I have a class that implements fu:

class Impl: public Proto{
public:
    void fu();
};

void Impl::fu(){
    printf("im fu");
}

And I have another class that needs to use fu implementation without knowing implementation itself:

class Invoke{
public:
    void useFu(void (Proto::*)());
};

Then I call useFu:

inv.useFu(static_cast<void (Proto::*)()>(&Impl::fu));

So my question is, how I call fu() in useFu(void (Proto::*)())?

void Invoke::useFu(void (Proto::*fu)()){
   fu() <--- how to use it?
};

I can`t call an abstract class method directly so I created some kind of pre-implementation:

class PreImpl: public Proto{
public:
    virtual void fu();
};

void PreImpl::fu()
{
    printf("I'm the wrong fu");
}

Then in useFu i call fu():

void Invoke::useFu(void (Proto::*fu)()){
    PreImpl preImpl;
    (static_cast<PreImpl>(preImpl).*fu)();
};

But after call of useFu i got a wrong function being executed:

void main(){
Invoke inv;

inv.useFu(static_cast<void (Proto::*)()>(&Impl::fu));
}

Prints out:

I'm the wrong fu

Aucun commentaire:

Enregistrer un commentaire