我从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上,如果我使用VS2012std::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>
特质可能以两种方式之一起作用:
decltype()
来自呼叫表达。result_type
typedefF
或在其中查找嵌套的result<T>
类模板F
(如果函子的参数数量大于零,因为可能存在重载)。如果使用后一种方法(2),则上述两种方法均不适用于lambda的类型,因此Boost最终会推导出 默认假设,void
以作为返回类型。
为了确保您的Boost实现将使用decltype()
运算符(可以很好地使用lambda的调用表达式),您需要在包含Boost标头之前预先定义一个定义:
#define BOOST_RESULT_OF_USE_DECLTYPE
或将此定义添加到boost/config/user.hpp
文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句