boost的类型::future<> from boost::async()

Type of boost::future<> from boost::async()

本文关键字:boost async from lt 类型 future gt      更新时间:2023-10-16

我从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<void>而不是boost::unique_future<int>

我做错了什么?

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

>boost::async需要确定参数函子调用的结果类型。为此,Boost 使用自己的boost::result_of<T>类模板实现。也就是说,async声明如下所示:

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

根据编译器的功能/提升的配置,boost::result_of<T>特征可能以以下两种方式之一工作:

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

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

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

#define BOOST_RESULT_OF_USE_DECLTYPE

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