[SOLVED] QThread run function with unknown number of arguments and types

Issue

I’m tyring to write a QThread function.
And in run function there is a function m_pFunc in the while loop.The m_pFunc is a function pointer with unknown number of arguments annd types.
How to achieve this function pointer?

void func1(int){ cout<<"func1"<<endl; }
void func2(int,char){ cout<<"func2"<<endl; }

class CThread: public QThread
{
    Q_OBJECT
    Q_DISABLE_COPY(CThread)

public:
    using PFunc = void (*)(...); //how to achieve it?
    CThread() = default;
    ~CThread() = default;
    CThread(const PFunc pFunc) :
        m_bRunning(false),
        m_pFunc(pFunc){
    };

protected:
    void run()
    {
        m_bRunning = true;
        while (m_bRunning) {
            m_pFunc(...);       //how to run this function pointer?
        }
    }

private:
    std::atomic_bool m_bRunning;
    PFunc m_pFunc;
};

CThread ct1(func1);
CThread ct2(func2);
ct1.run();
ct1.run();

expected result´╝Ü

func1
func2

Solution

class CThread: public QThread
{
    Q_OBJECT
    Q_DISABLE_COPY(CThread)

public:
    using PFunc = std::function<void()>; //use std::function
    CThread() = default;
    ~CThread() = default;

    template<class F>                    //template here
    CThread(F&& pFunc) :
        m_bRunning(false),
        m_pFunc(std::forward<F>(pFunc)){
    };

protected:
    void run()
    {
        m_bRunning = true;
        while (m_bRunning) {
            m_pFunc();           //call m_pFunc();
        }
    }

private:
    std::atomic_bool m_bRunning;
    PFunc m_pFunc;
};



CThread ct1(std::bind(func1,1));
CThread ct2(std::bind(func2,2,'a'));
ct1.run();
ct2.run();

Answered By – ssroreo

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *