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> 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 – 从中期期货创造未来?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)