c – 从中​​期期货创造未来?

c – 从中​​期期货创造未来?,第1张

概述在下面的示例代码中,我想从一个组件创建一个Item对象: struct Component { };struct Item { explicit Item(Component component) : comp(component) {} Component comp;};struct Factory { static std::future<Item> 在下面的示例代码中,我想从一个组件创建一个Item对象:
struct Component { };struct Item {    explicit Item(Component component) : comp(component) {}        Component comp;};struct Factory {    static std::future<Item> get_item() {        std::future<Component> component = get_component();                // how to get a std::future<Item> ?    }    std::future<Component> get_component();};

如何从std :: future< Component&gt to std :: future< Item>?

更新:从问题中删除我的第一个想法(这是线程),并发布了一个答案.

解决方法 需要moar packed_tasks!
std::future<Item> get_item() {    std::packaged_task<Item()> task([]{        return Item(get_component().get());    });    auto future = task.get_future();    std::thread(std::move(task)).detach();    return future;};

一般来说,我建议先忘记承诺和考虑packed_tasks. packed_task会为您维护(功能,承诺,未来)三重.它允许您以自然的方式(即返回和抛出等)来编写函数,并将异常正确传播到将来,您的示例被忽略(任何线程std ::中的未处理的异常终止您的程序!).

总结

以上是内存溢出为你收集整理的c – 从中​​期期货创造未来?全部内容,希望文章能够帮你解决c – 从中​​期期货创造未来?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1235877.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存