mardi 27 janvier 2015

How can I store generic packaged_tasks in a container?

I'm trying to take a 'task' in the style of std::async and store it in a container. I'm having to jump through hoops to achieve it, but I think there must be a better way.



std::vector<std::function<void()>> mTasks;

template<class F, class... Args>
std::future<typename std::result_of<typename std::decay<F>::type(typename std::decay<Args>::type...)>::type>
push(F&& f, Args&&... args)
{
auto func = std::make_shared<std::packaged_task<typename std::result_of<typename std::decay<F>::type(typename std::decay<Args>::type...)>::type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
auto future = func->get_future();

// for some reason I get a compilation error in clang if I get rid of the `=, ` in this capture:
mTasks.push_back([=, func = std::move(func)]{ (*func)(); });

return future;
}


So I'm using bind -> packaged_task -> shared_ptr -> lambda -> function. How can I do this better/more optimally? It would certainly be easier if there was a std::function which could take a non-copyable but moveable task. Can I std::forward args into the capture of a lambda, or do I have to use bind?


Aucun commentaire:

Enregistrer un commentaire