您还可以使用Herb Sutter提出的then
函数。这是一个稍微修改过的功能版本。有关它如何修改的更多信息以及与原始对话的链接可在this SO question中找到。您的代码将归结为:
return then(std::move(component), [](Component c) { return Item(c); });
最初的想法是让功能then
作为std::future<T>
一个成员函数并有一些正在进行的将其放入标准的工作。该函数的第二个版本用于void
期货(基本上只是异步链接功能)。正如Herb指出的那样,您可能需要额外的线程来支付使用这种方法的费用。
您的代码应该是这样的:
#include <future>
#include <thread>
#include <iostream>
template <typename T, typename Work>
auto then(std::future<T> f, Work w) -> std::future<decltype(w(f.get()))>
{
return std::async([](std::future<T> f, Work w)
{ return w(f.get()); }, std::move(f), std::move(w));
}
template <typename Work>
auto then(std::future<void> f, Work w) -> std::future<decltype(w())>
{
return std::async([](std::future<void> f, Work w) -> decltype(w())
{ f.wait(); return w(); }, std::move(f), std::move(w));
}
struct Component { };
struct Item {
Item(Component component) : comp(component) {}
Component comp;
};
struct Factory {
static std::future<Item> get_item() {
std::future<Component> component = get_component();
return then(std::move(component), [](Component c) { return Item(c); });
}
static std::future<Component> get_component()
{
return std::async([](){ return Component(); });
}
};
int main(int argc, char** argv)
{
auto f = Factory::get_item();
return 0;
}
上面的代码编译罚款铿锵或是libC++(在Mac OS X 10.8测试)。
属于上http://codereview.stackexchange.com? – 2013-02-14 14:30:32
一个侧面说明 - 更好地在Item的构造函数中使用const ref。 – 2013-02-14 14:31:27
@LightnessRacesinOrbit它如何评论问题? 。他正在寻找更好的方法/方式! – M3taSpl0it 2013-02-14 14:31:41