0

I'm trying to pass a pointer to a member function to a non member function as in the following example:

class Main
{
    static void runMain (void (*progress)(double))
    {
        for (int i=1; i<=100; ++i)
        {
            // Do something
            progress(i/100.0);
        }
    }
};

class A
{
    void setProgress (double) {/*Do something else*/}
    void runA ()
    {
        Main::runMain (&setProgress); // Error: incompatible parameter from void(A::*)(double) to void(*)(double)
    }
};

class B
{
    void updateProgress (double) {/*More things to do*/}
    void runB ()
    {
        Main::runMain (&updateProgress); // The same error
    }
};

This result with an error since the type function void( A::* )(double) passed from A to Main is not matching void( * )(double).

How can I pass the member function under the following constraint: I'm not allowed to change the structure of class A and B, except for the runA and runB implementation (but I can change class Main including its function signature).

Thanks!

1 Answers1

-2

So, probably you usually code in C#. In C++ pointer to a function (or static function) doesn't compitable with a pointer to a method (member function) of class.

Maybe passing-member-function-as-argument help you.

One of the possible solution:

class IProgressUpdater {
public:
    virtual void updateProgress( double ) = 0;
};

class Main
{
public:
    static void runMain ( IProgressUpdater* progressUpdater )
    {
        for (int i=1; i<=100; ++i)
        {
            // Do something
            progressUpdater->updateProgress( i/100.0 );
        }
    }
};

class A : public IProgressUpdater
{
    virtual void updateProgress( double ) {/*Do something else*/}
    void runA ()
    {
        Main::runMain( static_cast<IProgressUpdater*>( this ) );
    }
};

class B : public IProgressUpdater
{
    virtual void updateProgress( double ) {/*More things to do*/}
    void runB ()
    {
        Main::runMain( static_cast<IProgressUpdater*>( this ) );
    }
};
Community
  • 1
  • 1
Anton Todua
  • 667
  • 4
  • 15