将packaged_task移动到lambda

ron*_*nag 5 c++ lambda packaged-task c++11

我想移动并在lambda中调用boost :: packaged_task.

但是,我无法找到一个优雅的解决方案.

这不会编译.

        template<typename Func>
        auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
        {   
            typedef boost::packaged_task<decltype(func())> task_type;

            auto task = task_type(std::forward<Func>(func));
            auto future = task.get_future();

            execution_queue_.try_push([=]
            {
                try{task();}
                catch(boost::task_already_started&){}
            });

            return std::move(future);       
        }

    int _tmain(int argc, _TCHAR* argv[])
    {
        executor ex;
        ex.begin_invoke([]{std::cout << "Hello world!";});
       //error C3848: expression having type 'const boost::packaged_task<R>' would lose some const-volatile qualifiers in order to call 'void boost::packaged_task<R>::operator ()(void)'
//          with
//          [
//              R=void
//          ]
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我相当丑陋的解决方案:

    struct task_adaptor_t
    {
        // copy-constructor acts as move constructor
        task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
        task_adaptor_t(task_type&& task) : task(std::move(task)){}
        void operator()() const { task(); }
        mutable task_type task;
    } task_adaptor(std::move(task));

    execution_queue_.try_push([=]
    {
        try{task_adaptor();}
        catch(boost::task_already_started&){}
    });
Run Code Online (Sandbox Code Playgroud)

将packaged_task移动到调用它的lambda的"正确"方法是什么?

sel*_*tze 2

通过正确实现 std::bind (或与启用移动的类型相关的等效内容),您应该能够将 bind 和 C++0x lambda 结合起来,如下所示:

task_type task (std::forward<Func>(func));
auto future = task.get_future();

execution_queue_.try_push(std::bind([](task_type const& task)
{
    try{task();}
    catch(boost::task_already_started&){}
},std::move(task)));

return future;
Run Code Online (Sandbox Code Playgroud)

顺便说一句:您不需要 std::move 围绕 future,因为 future 是本地对象。因此,它已经受到潜在的复制省略的影响,如果编译器无法执行该省略,则它必须从“未来”移动构造返回值。在这种情况下显式使用 std::move 实际上可能会抑制复制/移动省略。