我很想寫一個QThread函式。
而在run函式中m_pFunc,在while回圈中m_pFunc有一個函式。它是一個函式指標,引數數量和型別未知。如何實作這個函式指標?
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();
預期結果:
FUNC1
FUNC2
uj5u.com熱心網友回復:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409024.html
標籤:
上一篇:在動態創建的QQuickPaintedItem中訪問引擎根背景關系
下一篇:從多個DLL版本中進行選擇
