gpt4 book ai didi

c++ - 将 packaged_task 移动到 lambda

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:36:53 28 4
gpt4 key购买 nike

我想在 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;
}

我相当丑陋的解决方案:

    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&){}
});

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

最佳答案

通过正确实现 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;

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

关于c++ - 将 packaged_task 移动到 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4483309/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com