0

I'm having a hard time to cast a pointer for a method in cpp from a different class. The method goes as follows:

The file that I'm passing the method:

void TimeCounterClass::DelayMili(uint8_t pMili, bool & pFlag, void(*doWhile)(void))
{
    tmpTicks = TimeSpan.Ticks + pMili;

    while ((!pFlag) && (TimeSpan.Ticks <= tmpTicks))
    {
        doWhile();
    }
}

The file that I'm trying to execute DelayMili:

bool lValue = false;

void AnotherClass::MessageArrive()
{
     // doSomething...
}

void AnotherClass::AnotherClass()
{
    TimeCounter.DelayMili(3000, lValue, (void(*)(void))(&MessageArrive)); // wrong casting
}
Rinaldi Segecin
  • 449
  • 8
  • 23
  • The problem is that `MessageArrive` is a member pointer with signature `void(MessageArrive::*)()`, not `void(*)()`. – AndyG Dec 29 '16 at 18:46
  • 1
    You need to wrap the member function appropriately to be able to pass it into `DelayMili`. Check out [this question](http://stackoverflow.com/a/41244621/27678) for how to do it in C++11+ or C++03 – AndyG Dec 29 '16 at 18:46
  • If you need to cast an object to a completely different type, most of the time you are doing something wrong. – Rakete1111 Dec 29 '16 at 18:48
  • 1
    That isn't the only problem. You can't pass `false` to a function expecting `bool&`. There's no "there" there. Now, how about posting a [minimal **complete** verifiable example](https://stackoverflow.com/help/mcve)? – WhozCraig Dec 29 '16 at 18:49
  • @Rakete1111: Agreed as a general rule of thumb, but type-erasure is a thing that has historically been shown to be good. OPs use case and the one I link to is also pretty reasonable. – AndyG Dec 29 '16 at 18:50
  • Thank you very much Andy. The implementation of your code it's simpler than it seems but I still struggle to understand it. I'll read a couple more times the breakdown you explained in the other post. – Rinaldi Segecin Dec 29 '16 at 22:03
  • 1
    @RinaldiSegecin: The C++03 style code I wrote in that post can be modified for your scenario. Replace `void(T::*PTR)()const` with `void(T::*PTR)()` wherever you find it. – AndyG Dec 30 '16 at 13:35
  • I noticed that, I wonder how did you find out about this. Thank you Andy. – Rinaldi Segecin Dec 30 '16 at 17:24

0 Answers0