繁体   English   中英

std :: async vs std :: promise

[英]std::async vs std::promise

我必须将getter函数包装到std::future对象中。
std::function<String (String)> -> std::function<std::future<String> (String)>

如此简单的问题,最好的/最快的方法是什么?

这是我想到的两个选择。

我有一个功能:

std::function<String (String)> getter;

然后使用std::promise将其包装:

std::function<std::future<String> (String)> binding = [getter](String context) {
    std::promise<String> p;
    p.set_value(getter(contex));
    return p.get_future();
};

或使用std::async

std::function<std::future<String> (String)> binding = [getter](String context) {
    return std::async(std::launch::deferred, getter, contex);
};

正确的答案是编写自己的make_ready_future (不属于std::experimantal make_ready_future )。 std::promise是我所知道的产生现成未来的唯一途径: async产生未就绪的未来。

这需要一个值,并产生该值的未来,并带有一些涉及引用包装的奇特的东西(您可以选择跳过)。

存在在C ++ 1z中添加它的建议,因此通过基于其接口创建自己的版本,可以对代码进行半过时验证。 另外,作为经过审核的设计,它的吸引力比您自己的要小。

编写完成后:

template<class F>
auto futuristic_wrapper( F&& f ) {
  return [f=std::forward<F>(f)](auto&&...args){
    return make_ready_future( f( decltype(args)(args)... ) );
  };
}

在C ++ 11中,您必须编写一个类来替换lambda:

template<class F>
struct futurize {
  F f;
  template<class...Args>
  operator()(Args&&...args)const->
  delctype(make_ready_future(f(std::forward<Args>(args)...)))
  { return make_ready_future(f(std::forward<Args>(args)...)); }
};
template<class F>
auto futuristic_wrapper( F&& f )->
futurize< typename std::decay_t<F>::type >
{
  return {std::forward<F>(f)};
}

这很烦人,但主要是机械转换。

实际上并不会产生std::function< future<R>(Args...) > ,但是它将返回可转换的内容。 如果我们毕竟不需要,则无需键入“擦除”。

您可以将从std::experimantal notstd窃取的“您自己的将要标准化的东西的版本” notstd类的命名空间中。 始终将其与notstd:: using namespace notstd; (永远不要using namespace notstd;并且不要using notstd::make_ready_future;因为将类型添加到std时该风险行为会发生变化),以便以后的用户清楚这不是它们的标准版本对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM