How to write a common callback function?



  • I have below code,

    #include <QCoreApplication>
    #include <QDebug>
    class Base
    {
      public:
        virtual void fun1() = 0;
    };
    class AAA: public Base
    {
    public:
        void fun1(){
            qWarning()<<__FUNCTION__<<__LINE__;
        }
    };
    
    class BBB: public Base
    {
    public:
        void fun1(){
            qWarning()<<__FUNCTION__<<__LINE__;
        }
    };
    
    typedef void (Base::*fun1)(void);
    class CCC
    {
    public:
        void run(fun1 f){
            f();
        }
    };
    
    int main(int argc, char *argv[])
    {
    
        AAA aaa;
        BBB bbb;
        CCC ccc;
        ccc.run(aaa.fun1); //run AAA::fun1
        ccc.run(bbb.fun1); //run BBB::fun1
        QCoreApplication a(argc, argv);
    
        return a.exec();
    }
    
    

    My purpose is that CCC::run() can call both AAA::fun1() and BBB::fun1(), but it doesn't compile.
    What is wrong?

    Thanks!


  • Moderators

    @Mr-Pang said in How to write a common callback function?:

    typedef void (Base::*fun1)(void);
    class CCC
    {
    public:
        void run(fun1 f){
            f();
        }
    };
    

    ...

    My purpose is that CCC::run() can call both AAA::fun1() and BBB::fun1()

    Base::fun1() is already a virtual method, so you should use C++ polymorphism:

    class CCC
    {
    public:
        void run(Base *b){
            b->fun1();
        }
    };
    
    int main(int argc, char *argv[])
    {
        AAA aaa;
        BBB bbb;
        CCC ccc;
        ccc.run(&aaa);
        ccc.run(&bbb);
    }
    

    it doesn't compile.
    What is wrong?

    Your compiler error message tells you what is wrong.



  • @JKSH
    Great! I never thought of it before.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.