boost :: future<>的类型来自boost :: async()

时间:2014-11-30 16:23:44

标签: c++ boost future boost-thread

我从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),它会按预期工作,并且将来的类型推断为{ {1}}。

1 个答案:

答案 0 :(得分:4)

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的配置,boost::result_of<T>特征可能有以下两种方式之一:

  1. 使用来自呼叫表达式的decltype()
  2. result_type中查找嵌套的F typedef或在result<T>中查找嵌套的F类模板(如果一些仿函数的参数大于零,则作为重载可能存在)。
  3. 如果使用后一种方法(2),上述两种方法都不适用于lambda类型,因此Boost以默认假设推导 void作为返回类型。< / p>

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

    #define BOOST_RESULT_OF_USE_DECLTYPE
    

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

相关问题