简体   繁体   中英

C++ 11 async programming using template

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM