Is it possible to pass function with arguments like this:
int func(int num)
{
return num;
}
to this function:
template<class T>
auto addTask(T task) -> std::future<decltype(task())>
{
auto wrapper = std::make_shared<std::packaged_task<decltype(task()) ()>>(std::move(task));
{
std::unique_lock<std::mutex> lock(mEventMutex);
mTasks.emplace([=] {
(*wrapper)();
});
}
mEventVar.notify_one();
return wrapper->get_future();
}
I know how pass function without agrs like this:
void func()
{}
It will be just:
addTask(func);
but can't find where to place args. Is it possible?
You could use a lambda that calls the function:
addTask([some_value]()
{
func(some_value);
});
Or rewrite addTask
to use template parameter packs for possible arguments:
template<typename Func, typename ...Args>
auto addTask(Func task, Args... arguments) -> std::future<decltype(task(arguments...))>
{
auto wrapper = std::make_shared<std::packaged_task<decltype(task(arguments...)) (Args...)>>(std::move(task));
{
std::unique_lock<std::mutex> lock(mEventMutex);
mTasks.emplace([=] {
(*wrapper)(std::forward<Args>(arguments)...);
});
}
mEventVar.notify_one();
return wrapper->get_future();
}
addTask(func, some_value);
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.