【问题标题】:Type of boost::future<> from boost::async()boost::future<> 的类型来自 boost::async()
【发布时间】:2014-11-30 16:23:44
【问题描述】:

boost::async()(Boost 1.56,Windows:VS2010 和 VS2012)给我带来了意想不到的结果。

#include <boost/thread/future.hpp>
...
auto func = [](){ return 123; };
auto boostFut = boost::async(func);
// boostFut = 42; // intentional error to reveal deduced type in compilation error

由于某种原因,boostFut 被推断为boost::unique_future&lt;void&gt; 而不是boost::unique_future&lt;int&gt;

我做错了什么?

注意: 在 VS2012 上,如果我使用 std::async(func) 而不是 boost::async(func),它会按预期工作,并且未来的 type 被推断为 int

【问题讨论】:

  • boost 的版本很有用。哦,有时 boost 函数在传入的函数对象中需要 result_type typedef。
  • 如上所述:Boost 1.56。您能否详细说明result_type 的建议?即使我明确定义,问题仍然存在:boost::unique_future&lt;int&gt; boostFut = ... 在这种情况下,asyn() 分配无法编译。
  • 抱歉错过了。我知道一些 boost 函数适配器要求结果类型在传入的对象中是显式的,或者如果它们无法解决问题,至少会依赖该类型。你的问题会随着函数指针而消失吗? struct foo { typedef int result_type; int operator()() const { return 42; };?没有result_typefoo
  • @AdiShavit 在包含 boost 库之前尝试添加 #define BOOST_RESULT_OF_USE_DECLTYPE
  • @PiotrS.:成功了!这是在哪里记录的?把它写成答案,我会标记它。

标签: c++ boost future boost-thread


【解决方案1】:

boost::async 需要确定参数仿函数调用的结果类型。为了做到这一点,Boost 使用自己的boost::result_of&lt;T&gt; 类模板实现。也就是说,async 声明如下:

template <class F>
boost::future<typename boost::result_of<typename boost::decay<F>::type()>::type>
async(F f);

根据编译器的功能/提升的配置,boost::result_of&lt;T&gt; trait 可能以以下两种方式之一工作:

  1. 在调用表达式中使用decltype()
  2. F 中查找嵌套的result_type typedef 或在F 中查找嵌套的result&lt;T&gt; 类模板(如果函子的参数数量大于零,则可能存在重载)。

如果使用后一种方法 (2),则上述替代方法都不适用于 lambda 的类型,因此 Boost 最终以默认假设 deducing void 作为返回类型。

为确保您的 Boost 实现将使用 decltype() 运算符(适用于 lambda 的调用表达式),您需要在包含 Boost 标头之前添加一个定义:

#define BOOST_RESULT_OF_USE_DECLTYPE

或将此定义添加到boost/config/user.hpp 文件中。

【讨论】:

  • 很好的答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 2014-05-05
  • 2012-08-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多