[英]C++ 11 async programming using template
我正在寫一個類來實現任務功能。 這是我的代碼:
template<typename TType>
class YHMTask
{
public:
YHMTask() {};
std::future<TType> mTask;
};
template<typename T>
YHMTask<T> YHMCreateTask(std::function<T()> func)
{
YHMTask<T> yhmTask;
yhmTask.mTask = std::async(func);
return yhmTask;
}
如果我沒有在YHMCreateTask中使用模板,則可以這樣使用它:
YHMCreateTask([]{return 12;});
但是當我使用模板編寫此函數時。 編譯器報告此錯誤:
error C2672: 'YHMCreateTask': no matching overloaded function found
error C2784: 'YHMTask<TType> YHMCreateTask(std::function<_Type(void)>)': could not deduce template argument for 'std::function<_Type(void)>' from 'main::<lambda_a66b482c6cd6dab7208879904592bde5>'
我必須像這樣使用YHMCreateTask:
int TestFunc()
{
return 11;
}
...
std::function<int(void)> funInt = TestFunc;
auto taskNew = YHMCreateTask(funInt);
我希望可以像YHMCreateTask([] {return 12;});一樣使用YHMCreateTask。 我應該怎么做?
您必須使用類似:
template<typename F>
auto YHMCreateTask(F func)
-> YHMTask<decltype(func())>
{
YHMTask<decltype(func())> yhmTask;
yhmTask.mTask = std::async(func);
return yhmTask;
}
無法從lamdba推導T
來構造std::function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.