Reputation: 222
I'm writing a class to achieve task feature. Here is my code:
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;
}
If I didn't use template in YHMCreateTask, I can use it like this:
YHMCreateTask([]{return 12;});
But when I writing this function using template. Compiler report this error:
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>'
I have to use YHMCreateTask like this:
int TestFunc()
{
return 11;
}
...
std::function<int(void)> funInt = TestFunc;
auto taskNew = YHMCreateTask(funInt);
I want YHMCreateTask can be used like YHMCreateTask([]{return 12;}); How should I do?
Upvotes: 1
Views: 317
Reputation: 218228
You have to use something like:
template<typename F>
auto YHMCreateTask(F func)
-> YHMTask<decltype(func())>
{
YHMTask<decltype(func())> yhmTask;
yhmTask.mTask = std::async(func);
return yhmTask;
}
T
cannot be deduced from lamdba to construct std::function
Upvotes: 2