您還可以使用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