我有一個ThreadPool
類的enqueue
功能:C++模板 - 可變參數模板和路過常引用
class ThreadPool
{
public:
//(Code removed here)
template <typename ... Args, typename Fun>
JobId enqueue(Fun func, Args ... args);
//(Code removed here)
}
我用它在這些非靜態成員函數loadStuff
上Object
類:
class Object
{
//(Code removed here)
void init(const PrepareData & prepareData);
virtual bool loadStuff(const PrepareData & prepareData);
//(Code removed here)
}
通過調用QObject :: init:
void QObject::init(const PrepareData &prepareData)
{
threadPool->enqueue(&loadStuff, this, prepareData);
}
但我注意到prepareData是通過複製傳遞的,這會消耗大量的內存並顯着減慢程序的速度(並且是無用的)。
所以我刪除了PrepareData中的copy ctor和賦值操作符。該程序不再編譯,因爲可變參數模板通過值而不是參考來獲取參數。
因此,我宣佈排隊按引用傳遞的可變參數模板參數:
template <typename ... Args, typename Fun>
JobId enqueue(Fun func, Args&... args);
現在拷貝構造函數不再被調用,但我得到以下錯誤:
object.cpp:21: error: no matching function for call to
'ThreadPool::enqueue(bool (Object::*)(const PrepareData&), Object *, const PrepareData&)' threadPool->enqueue(&prepareType, this, loadStuff);
所以我如何做到這一點,我相當遺憾。我可以,而不是通過const PrepareData &
,通過const PrepareData *
副本,但我想了解爲什麼它不適用於const引用。
說'參數數量&& ...'。 –