从中间期货创造未来? [英] Creating a future from intermediate futures?

查看:107
本文介绍了从中间期货创造未来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例代码中,我要从组件中创建

In the following sample code I want to create an Item object from a Component:

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> std :: future< Item>


更新: / b>从问题中删除了我的第一个想法(这是基于线程的)并发布了一个答案。


Update: removed my first idea (which was thread-based) from the question and posted an answer.

推荐答案

我可以使用延迟启动策略使用 std :: async 来组成最终对象:

It occurred to me that I can use std::async with the deferred launch policy to compose the final object:

std::future<Item> get_item()
{
    // start async creation of component
    // (using shared_future to make it copyable)
    std::shared_future<Component> component = get_component();

    // deferred launch policy can be used for construction of the final object
    return std::async(std::launch::deferred, [=]() {
        return Item(component.get());
    });
}

这篇关于从中间期货创造未来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆